<?php

namespace App\Modules\HR\Overtime\Repositories;

use App\Modules\HR\Overtime\Models\OvertimeRatePolicy;
use App\Support\Lists\ListQuery;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Request;

class OvertimeRatePolicyRepository
{
    public function defaultForTenant(int $tenantId): ?OvertimeRatePolicy
    {
        return OvertimeRatePolicy::query()
            ->where('tenant_id', $tenantId)
            ->where('is_active', true)
            ->orderByDesc('is_default')
            ->orderBy('id')
            ->first();
    }

    public function paginateForIndex(int $tenantId, Request $request): LengthAwarePaginator
    {
        $query = OvertimeRatePolicy::query()->where('tenant_id', $tenantId);

        ListQuery::applySearch($query, $request->input('q'), ['name']);
        ListQuery::applyBoolean($query, 'is_active', $request->input('is_active'));
        ListQuery::applySort(
            $query,
            $request->input('sort'),
            $request->input('dir'),
            [
                'name' => 'name',
                'is_default' => 'is_default',
                'is_active' => 'is_active',
            ],
            'name',
        );

        return ListQuery::paginate($query, $request);
    }

    public function findForTenant(int $tenantId, int $id): ?OvertimeRatePolicy
    {
        return OvertimeRatePolicy::query()
            ->where('tenant_id', $tenantId)
            ->whereKey($id)
            ->first();
    }

    /**
     * @param  array<string, mixed>  $data
     */
    public function create(array $data): OvertimeRatePolicy
    {
        return OvertimeRatePolicy::query()->create($data);
    }

    /**
     * @param  array<string, mixed>  $data
     */
    public function update(OvertimeRatePolicy $policy, array $data): OvertimeRatePolicy
    {
        $policy->update($data);

        return $policy->fresh();
    }

    /**
     * Clear the default flag for every other active/inactive policy in the tenant.
     */
    public function clearDefaultForTenant(int $tenantId, ?int $exceptId = null): int
    {
        $query = OvertimeRatePolicy::query()
            ->where('tenant_id', $tenantId)
            ->where('is_default', true);

        if ($exceptId !== null) {
            $query->where('id', '!=', $exceptId);
        }

        return $query->update(['is_default' => false]);
    }
}
