<?php

namespace App\Services\Admin\Master;

use App\Enums\UserRole;
use App\Models\Course;
use App\Models\User;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;

class CourseService
{
    public function paginated(User $user, int $perPage = 25, string $search = '', ?int $departmentId = null, ?int $semesterNumber = null): LengthAwarePaginator
    {
        return Course::query()
            ->join('departments', 'departments.id', '=', 'courses.department_id')
            ->with('department:id,name')
            ->when($search, fn ($q) => $q->where('courses.name', 'like', "%{$search}%")->orWhere('courses.code', 'like', "%{$search}%"))
            ->when($departmentId, fn ($q) => $q->where('courses.department_id', $departmentId))
            ->when($semesterNumber, fn ($q) => $q->where('courses.semester_number', $semesterNumber))
            ->when($user->hasRole(UserRole::Mahasiswa->value), fn ($q) => $q->where('courses.department_id', $user->student?->department_id))
            ->when($user->hasRole(UserRole::Dosen->value), fn ($q) => $q->whereIn('courses.department_id', $user->lecturer?->departments()->pluck('departments.id') ?? []))
            ->orderBy('departments.name')
            ->orderBy('courses.semester_number')
            ->orderBy('courses.name')
            ->paginate($perPage, ['courses.id', 'courses.code', 'courses.name', 'courses.credits', 'courses.department_id', 'courses.semester_number']);
    }

    public function create(array $data): Course
    {
        return Course::create($data);
    }

    public function update(Course $course, array $data): Course
    {
        $course->update([
            'code' => $data['code'],
            'name' => $data['name'],
            'credits' => $data['credits'],
            'department_id' => $data['department_id'],
            'semester_number' => $data['semester_number'] ?? null,
        ]);

        return $course;
    }

    public function delete(Course $course): bool
    {
        return $course->delete();
    }

    public function getAllForSelect(): Collection
    {
        return Course::query()
            ->join('departments', 'departments.id', '=', 'courses.department_id')
            ->with('department:id,name')
            ->orderBy('departments.name')
            ->orderBy('courses.semester_number')
            ->orderBy('courses.name')
            ->get(['courses.id', 'courses.code', 'courses.name', 'courses.department_id', 'courses.semester_number']);
    }

    public function getSemesterNumbers(): array
    {
        return Course::query()
            ->whereNotNull('semester_number')
            ->distinct()
            ->orderBy('semester_number')
            ->pluck('semester_number')
            ->all();
    }
}
