<?php

namespace App\Services\Admin\AcademicClasses;

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

class MaterialService
{
    public function paginated(User $user, int $perPage = 25, string $search = '', ?int $courseClassId = null): LengthAwarePaginator
    {
        return Material::query()
            ->select(['id', 'course_class_id', 'title', 'description', 'meeting_number'])
            ->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))
            ->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): Material
    {
        $material = Material::create([
            'course_class_id' => $data['course_class_id'],
            'title' => $data['title'],
            'description' => $data['description'] ?? null,
            'meeting_number' => $data['meeting_number'] ?? null,
        ]);

        if ($file) {
            $material->addMedia($file)->toMediaCollection('materials');
        }

        return $material;
    }

    public function update(Material $material, array $data, ?UploadedFile $file): Material
    {
        $material->course_class_id = $data['course_class_id'];
        $material->title = $data['title'];
        $material->description = $data['description'] ?? null;
        $material->meeting_number = $data['meeting_number'] ?? null;
        $material->update();

        if ($file) {
            $material->addMedia($file)->toMediaCollection('materials');
        }

        return $material;
    }

    public function delete(Material $material): bool
    {
        return $material->delete();
    }
}
