<?php

namespace App\Modules\HR\Overtime\Services;

use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\HR\Overtime\DTOs\OvertimeRequestSubmitData;
use App\Modules\HR\Overtime\Models\OvertimeRequest;
use App\Modules\HR\Overtime\Repositories\OvertimeRequestRepository;
use App\Modules\HR\Overtime\Support\OvertimeRequestStatus;
use Carbon\CarbonImmutable;

class OvertimeRequestService
{
    public function __construct(
        private readonly OvertimeRequestRepository $requests,
    ) {}

    public function submit(Tenant $tenant, OvertimeRequestSubmitData $data, int $userId): OvertimeRequest
    {
        return $this->requests->create([
            'tenant_id' => $tenant->id,
            'employee_id' => $data->employeeId,
            'requested_by' => $userId,
            'attendance_date' => CarbonImmutable::parse($data->attendanceDate)->toDateString(),
            'overtime_minutes' => $data->overtimeMinutes,
            'reason' => $data->reason,
            'status' => OvertimeRequestStatus::PENDING,
        ]);
    }

    /**
     * Preferred payroll input: approved OT minutes when any approved request exists
     * in the range; otherwise null so callers can use attendance overtime_minutes.
     */
    public function approvedOvertimeMinutesForEmployeeInRange(
        int $tenantId,
        int $employeeId,
        string $from,
        string $to,
    ): ?int {
        return $this->requests->approvedOvertimeMinutesForEmployeeInRange(
            $tenantId,
            $employeeId,
            $from,
            $to,
        );
    }
}
