<?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\DTOs\ShiftTimeContext;
use App\Modules\HR\Shifts\Support\ShiftScheduleEndpoints;
use Carbon\CarbonImmutable;

class AttendancePolicyMetricsService
{
    public function __construct(
        private readonly AttendancePolicyRepository $policies,
        private readonly EarlyLeaveDetectionService $earlyLeave,
    ) {}

    public function latenessThreshold(
        int $tenantId,
        ShiftTimeContext $context,
        CarbonImmutable $date,
    ): CarbonImmutable {
        $grace = $this->policies->forTenant($tenantId)?->late_grace_minutes;
        if ($grace === null) {
            return $context->latenessThreshold;
        }

        return ShiftScheduleEndpoints::shiftStartOnDate($context->shift, $date)
            ->addMinutes((int) $grace);
    }

    public function earlyLeaveNote(
        Employee $employee,
        string $date,
        CarbonImmutable $checkOut,
    ): string {
        $minutes = $this->earlyLeave->minutes($employee, $date, $checkOut);

        return $minutes > 0 ? __('attendance.notes.early_leave', ['minutes' => $minutes]) : '';
    }
}
