<?php

namespace App\Services\Admin\Master;

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

class DepartmentService
{
    public function getAllForSelect(): Collection
    {
        return Department::select(['id', 'code', 'name', 'degree_level'])->get();
    }

    public function paginated(int $perPage = 25, string $search = ''): LengthAwarePaginator
    {
        return Department::query()
            ->select(['id', 'code', 'name', 'degree_level'])
            ->when($search, fn ($q) => $q->where('name', 'like', "%{$search}%")->orWhere('code', 'like', "%{$search}%"))
            ->latest()
            ->paginate($perPage);
    }

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

    public function update(Department $department, array $data): Department
    {
        $department->code = $data['code'];
        $department->name = $data['name'];
        $department->degree_level = $data['degree_level'] ?? null;
        $department->update();

        return $department;
    }

    public function delete(Department $department): bool
    {
        return $department->delete();
    }
}
