<?php

namespace App\Services\Admin\Manage;

use App\Enums\RegistrationStatus;
use App\Models\ClassEnrollment;
use App\Models\CourseRegistration;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class CourseRegistrationService
{
    public function paginated(int $perPage = 25, string $search = '', ?string $status = null, ?int $academicTermId = null): LengthAwarePaginator
    {
        return CourseRegistration::query()
            ->select(['id', 'student_id', 'academic_term_id', 'course_class_id', 'status', 'approved_by', 'created_at'])
            ->with([
                'student.user.profile',
                'student.department',
                'academicTerm:id,name,semester,start_date,end_date',
                'courseClass.course:id,code,name',
                'approver.user.profile',
            ])
            ->when($search, fn ($q) => $q->whereHas('student', fn ($q) => $q->where('student_number', 'like', "%{$search}%")
                ->orWhereHas('user.profile', fn ($q) => $q->where('full_name', 'like', "%{$search}%"))))
            ->when($status, fn ($q) => $q->where('status', $status))
            ->when($academicTermId, fn ($q) => $q->where('academic_term_id', $academicTermId))
            ->latest()
            ->paginate($perPage);
    }

    public function create(array $data): CourseRegistration
    {
        $registration = CourseRegistration::create([
            'student_id' => $data['student_id'],
            'academic_term_id' => $data['academic_term_id'],
            'course_class_id' => $data['course_class_id'],
            'status' => $data['status'] ?? RegistrationStatus::Submitted->value,
            'approved_by' => $data['approved_by'] ?? null,
        ]);

        $this->syncEnrollment($registration);

        return $registration;
    }

    public function update(CourseRegistration $registration, array $data): CourseRegistration
    {
        $registration->student_id = $data['student_id'];
        $registration->academic_term_id = $data['academic_term_id'];
        $registration->course_class_id = $data['course_class_id'];
        $registration->status = $data['status'] ?? RegistrationStatus::Submitted->value;
        $registration->approved_by = $data['approved_by'] ?? null;
        $registration->update();

        $this->syncEnrollment($registration);

        return $registration;
    }

    public function delete(CourseRegistration $registration): bool
    {
        return $registration->delete();
    }

    private function syncEnrollment(CourseRegistration $registration): void
    {
        if ($registration->status !== RegistrationStatus::Approved) {
            return;
        }

        ClassEnrollment::firstOrCreate(
            [
                'course_class_id' => $registration->course_class_id,
                'student_id' => $registration->student_id,
            ],
            [
                'enrolled_at' => now(),
            ],
        );
    }
}
