<?php

namespace Modules\Employee\Repositories;

use Illuminate\Support\Facades\DB;
use Modules\Core\Enums\StatusEnum;
use Modules\Employee\DTO\EmployeeSettingFilter;
use Modules\Employee\Models\Designation;


class DesignationRepository
{
    public function all(EmployeeSettingFilter $filter)
    {
        return Designation::when(
            $this->getRelationName($filter->type),
            fn($q, $relation) => $q->with($relation)
        )->when($filter->search, function ($query, $search) {

            $search = '%' . trim($search) . '%';

            $query->where(function ($q) use ($search) {
                $q->where('name', 'LIKE', $search);
            });
        })
            ->when(
                $filter->status,
                fn($q, $status) =>
                $q->where('status', $status)
            )
            ->orderBy('name')
            ->paginate($filter->perPage ?? 15);
    }

    private function getRelationName(?string $type)
    {
        return match ($type) {
            'salary_grade'   => 'salaryGrade',
            'staff_type' => 'staffType',
            'all' => [
                'salaryGrade',
                'staffType',
            ],
            default => null,
        };
    }


    public function find($id)
    {
        $designation = Designation::findOrFail($id);
        return $designation;
    }

    public function create(array $data)
    {
        $designation = Designation::create([
            'name'       => $data['name'],
            'staff_type_id' => $data['staff_type_id'] ?? null,
            'salary_grade_id' => $data['salary_grade_id'] ?? null,
            'status'     => $data['status'] ?? StatusEnum::ACTIVE,
        ]);
        return $designation;
    }

    public function update(Designation $designation, array $data)
    {
        $designation->update([
            'name'       => $data['name'],
            'staff_type_id' => $data['staff_type_id'] ?? null,
            'salary_grade_id' => $data['salary_grade_id'] ?? null,
            'status'     => $data['status'] ?? StatusEnum::ACTIVE,
        ]);
        return $designation;
    }

    public function updateStatus(Designation $designation, array $status)
    {
        $designation->update([
            'status' => $status['status'] ?? StatusEnum::ACTIVE,
        ]);

        return $designation;
    }
}
