<?php

namespace App\Modules\HR\Overtime\Repositories;

use App\Modules\HR\Overtime\Models\OvertimeRequest;
use App\Modules\HR\Overtime\Support\OvertimeRequestStatus;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

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

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

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

    public function paginateForTenant(int $tenantId, int $perPage = 20): LengthAwarePaginator
    {
        return OvertimeRequest::query()
            ->where('tenant_id', $tenantId)
            ->with(['employee'])
            ->orderByDesc('attendance_date')
            ->paginate($perPage);
    }

    /**
     * Sum of approved overtime minutes. Returns null when no approved rows exist
     * so payroll can fall back to attendance overtime_minutes storage.
     */
    public function approvedOvertimeMinutesForEmployeeInRange(
        int $tenantId,
        int $employeeId,
        string $from,
        string $to,
    ): ?int {
        $base = OvertimeRequest::query()
            ->where('tenant_id', $tenantId)
            ->where('employee_id', $employeeId)
            ->where('status', OvertimeRequestStatus::APPROVED)
            ->whereBetween('attendance_date', [$from, $to]);

        if (! (clone $base)->exists()) {
            return null;
        }

        return (int) $base->sum('overtime_minutes');
    }

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

        return $row->fresh(['employee']);
    }
}
