<?php

namespace App\Services\Admin\Master;

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

class CourseService
{
    public function getAllForSelect(): Collection
    {
        return Course::select(['id', 'code', 'name', 'department_id'])->get();
    }

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

    public function paginated(int $perPage = 25, string $search = '', ?int $departmentId = null, ?int $semesterNumber = null): LengthAwarePaginator
    {
        return Course::query()
            ->select(['id', 'code', 'name', 'credits', 'department_id', 'semester_number'])
            ->with('department:id,name')
            ->when($search, fn ($q) => $q->where('name', 'like', "%{$search}%")->orWhere('code', 'like', "%{$search}%"))
            ->when($departmentId, fn ($q) => $q->where('department_id', $departmentId))
            ->when($semesterNumber, fn ($q) => $q->where('semester_number', $semesterNumber))
            ->latest()
            ->paginate($perPage);
    }

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

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

        return $course;
    }

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