<?php

namespace App\Services\Admin\AcademicClasses;

use App\Enums\AssignmentStatus;
use App\Enums\RegistrationStatus;
use App\Models\Assignment;
use App\Models\User;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\UploadedFile;

class AssignmentService
{
    public function paginated(User $user, int $perPage = 25, string $search = '', ?int $courseClassId = null, ?int $academicTermId = null): LengthAwarePaginator
    {
        return Assignment::query()
            ->select(['id', 'course_class_id', 'title', 'description', 'deadline', 'status'])
            ->withCount([
                'submissions',
                'submissions as graded_submissions_count' => fn ($q) => $q->whereNotNull('score'),
            ])
            ->with(['courseClass' => fn ($q) => $q->withCount('enrollments')
                ->with(['course:id,code,name', 'academicTerm:id,academic_year,semester,start_date,end_date'])])
            ->when($user->hasRole('mahasiswa'), fn ($q) => $q->with(['submissions' => function ($q) use ($user) {
                $q->select(['id', 'assignment_id', 'student_id', 'notes', 'status', 'submitted_at'])
                    ->where('student_id', $user->student?->id);
            }]))
            ->when($search, fn ($q) => $q->where('title', 'like', "%{$search}%"))
            ->when($courseClassId, fn ($q) => $q->where('course_class_id', $courseClassId))
            ->when($academicTermId, fn ($q) => $q->whereHas('courseClass', fn ($q) => $q->where('academic_term_id', $academicTermId)))
            ->when($user->hasRole('dosen'), fn ($q) => $q->whereHas('courseClass', fn ($q) => $q->where('lecturer_id', $user->lecturer?->id)))
            ->when($user->hasRole('mahasiswa'), fn ($q) => $q->whereHas('courseClass', function ($q) use ($user) {
                $q->whereHas('registrations', function ($q) use ($user) {
                    $q->where('student_id', $user->student?->id)
                        ->whereHas('submission', fn ($q) => $q->where('status', RegistrationStatus::Approved));
                });
            }))
            ->latest()
            ->paginate($perPage);
    }

    public function create(array $data, ?UploadedFile $file): Assignment
    {
        $assignment = Assignment::create([
            'course_class_id' => $data['course_class_id'],
            'title' => $data['title'],
            'description' => $data['description'] ?? null,
            'deadline' => $data['deadline'],
            'status' => $data['status'] ?? AssignmentStatus::Open,
        ]);

        if ($file) {
            $assignment->addMedia($file)->toMediaCollection('assignment_attachment');
        }

        return $assignment;
    }

    public function update(Assignment $assignment, array $data, ?UploadedFile $file): Assignment
    {
        $assignment->course_class_id = $data['course_class_id'];
        $assignment->title = $data['title'];
        $assignment->description = $data['description'] ?? null;
        $assignment->deadline = $data['deadline'];
        $assignment->status = $data['status'] ?? $assignment->status;
        $assignment->update();

        if ($file) {
            $assignment->addMedia($file)->toMediaCollection('assignment_attachment');
        }

        return $assignment;
    }

    public function delete(Assignment $assignment): bool
    {
        return $assignment->delete();
    }
}
