<?php

namespace App\Services\Admin\Manage;

use App\Models\CourseClass;
use App\Models\User;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;

class CourseClassService
{
    /**
     * When $user is a dosen, only their own assigned classes are returned.
     * When $user is a mahasiswa, only classes from their own department are returned.
     */
    public function getAllForSelect(?User $user = null): Collection
    {
        return CourseClass::query()
            ->select(['course_classes.id', 'course_classes.course_id', 'course_classes.lecturer_id', 'course_classes.academic_term_id'])
            ->join('courses', 'courses.id', '=', 'course_classes.course_id')
            ->join('departments', 'departments.id', '=', 'courses.department_id')
            ->with([
                'course:id,code,name,semester_number,department_id',
                'course.department:id,name',
            ])
            ->when($user?->hasRole('dosen'), fn ($q) => $q->where('course_classes.lecturer_id', $user->lecturer?->id))
            ->when($user?->hasRole('mahasiswa'), fn ($q) => $q->where('courses.department_id', $user->student?->department_id))
            ->orderBy('departments.name')
            ->orderBy('courses.semester_number')
            ->orderBy('courses.name')
            ->get();
    }

    public function paginated(int $perPage = 25, string $search = '', ?int $academicTermId = null, ?string $method = null): LengthAwarePaginator
    {
        return CourseClass::query()
            ->select(['course_classes.id', 'course_classes.course_id', 'course_classes.lecturer_id', 'course_classes.academic_term_id', 'course_classes.method'])
            ->join('academic_terms', 'academic_terms.id', '=', 'course_classes.academic_term_id')
            ->join('courses', 'courses.id', '=', 'course_classes.course_id')
            ->withCount('enrollments')
            ->with(['course:id,code,name,department_id,semester_number', 'lecturer.user.profile', 'academicTerm:id,academic_year,semester,start_date,end_date'])
            ->when($search, fn ($q) => $q->whereHas('course', fn ($q) => $q->where('name', 'like', "%{$search}%")->orWhere('code', 'like', "%{$search}%")))
            ->when($academicTermId, fn ($q) => $q->where('course_classes.academic_term_id', $academicTermId))
            ->when($method, fn ($q) => $q->where('course_classes.method', $method))
            ->orderByDesc('academic_terms.start_date')
            ->orderBy('courses.semester_number')
            ->orderBy('courses.name')
            ->paginate($perPage);
    }

    /**
     * @param  array{course_ids: array<int, int>, lecturer_id: int, academic_term_id: int, method?: string|null}  $data
     * @return Collection<int, CourseClass>
     */
    public function createMany(array $data): Collection
    {
        return new Collection(array_map(fn (int $courseId) => CourseClass::create([
            'course_id' => $courseId,
            'lecturer_id' => $data['lecturer_id'],
            'academic_term_id' => $data['academic_term_id'],
            'method' => $data['method'] ?? null,
        ]), $data['course_ids']));
    }

    public function update(CourseClass $courseClass, array $data): CourseClass
    {
        $courseClass->course_id = $data['course_id'];
        $courseClass->lecturer_id = $data['lecturer_id'];
        $courseClass->academic_term_id = $data['academic_term_id'];
        $courseClass->method = $data['method'] ?? null;
        $courseClass->update();

        return $courseClass;
    }

    public function delete(CourseClass $courseClass): bool
    {
        return $courseClass->delete();
    }

    /**
     * Copies every course class from one academic term into another,
     * skipping courses that already have a class in the target term.
     *
     * @return array{created: int, skipped: int}
     */
    public function duplicateFromTerm(int $sourceAcademicTermId, int $targetAcademicTermId): array
    {
        return DB::transaction(function () use ($sourceAcademicTermId, $targetAcademicTermId) {
            $sourceClasses = CourseClass::query()
                ->where('academic_term_id', $sourceAcademicTermId)
                ->get(['course_id', 'lecturer_id', 'method']);

            $existingCourseIds = CourseClass::query()
                ->where('academic_term_id', $targetAcademicTermId)
                ->pluck('course_id')
                ->all();

            $created = 0;
            $skipped = 0;

            foreach ($sourceClasses as $sourceClass) {
                if (in_array($sourceClass->course_id, $existingCourseIds, true)) {
                    $skipped++;

                    continue;
                }

                CourseClass::create([
                    'course_id' => $sourceClass->course_id,
                    'lecturer_id' => $sourceClass->lecturer_id,
                    'academic_term_id' => $targetAcademicTermId,
                    'method' => $sourceClass->method,
                ]);

                $existingCourseIds[] = $sourceClass->course_id;
                $created++;
            }

            return ['created' => $created, 'skipped' => $skipped];
        });
    }
}
