<?php

namespace App\Modules\HR\Attendance\Services;

use App\Modules\HR\Attendance\Repositories\AttendancePolicyRepository;
use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\Shifts\Services\ShiftResolutionService;
use App\Modules\HR\Shifts\Support\ShiftScheduleEndpoints;
use Carbon\CarbonImmutable;

class EarlyLeaveDetectionService
{
    public function __construct(
        private readonly AttendancePolicyRepository $policies,
        private readonly ShiftResolutionService $shifts,
    ) {}

    public function minutes(Employee $employee, string $date, CarbonImmutable $checkOut): int
    {
        $policy = $this->policies->forTenant((int) $employee->tenant_id);
        if ($policy === null || ! $policy->enable_early_leave_detection) {
            return 0;
        }
        $context = $this->shifts->resolveContextForAttendanceDate($employee, $date, $checkOut);
        if ($context === null) {
            return 0;
        }
        $day = CarbonImmutable::parse($date, $checkOut->getTimezone());
        $end = ShiftScheduleEndpoints::shiftEndOnDate($context->shift, $day)
            ->subMinutes((int) $policy->early_leave_grace_minutes);

        return $checkOut->lt($end) ? $checkOut->diffInMinutes($end) : 0;
    }
}
