<?php

namespace App\Services\Admin\AcademicClasses;

use App\Models\Assignment;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\UploadedFile;

class AssignmentService
{
    public function paginated(int $perPage = 25, string $search = '', ?int $courseClassId = null): LengthAwarePaginator
    {
        return Assignment::query()
            ->select(['id', 'course_class_id', 'title', 'description', 'deadline'])
            ->withCount('submissions')
            ->with('courseClass.course:id,code,name')
            ->when($search, fn ($q) => $q->where('title', 'like', "%{$search}%"))
            ->when($courseClassId, fn ($q) => $q->where('course_class_id', $courseClassId))
            ->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'],
        ]);

        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->update();

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

        return $assignment;
    }

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