<?php

namespace App\Modules\HR\Overtime\Services;

use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\HR\Attendance\Repositories\AttendanceRecordRepository;
use App\Modules\HR\Employees\Models\Employee;
use Illuminate\Support\Collection;

class OvertimeCreatePageService
{
    public function __construct(
        private readonly AttendanceRecordRepository $attendance,
    ) {}

    /**
     * @return array{
     *     employees: Collection<int, Employee>,
     *     selectedEmployeeId: int|null,
     *     selectedAttendanceDate: string|null,
     *     suggestedOvertimeMinutes: int|null
     * }
     */
    public function forHrCreate(Tenant $tenant, ?int $employeeId, ?string $attendanceDate): array
    {
        $date = $this->normalizeDate($attendanceDate);
        $minutes = $this->suggestedMinutes((int) $tenant->id, $employeeId, $date);

        return [
            'employees' => Employee::query()
                ->where('tenant_id', $tenant->id)
                ->orderBy('full_name')
                ->get(),
            'selectedEmployeeId' => $employeeId,
            'selectedAttendanceDate' => $date,
            'suggestedOvertimeMinutes' => $minutes,
        ];
    }

    public function suggestedMinutes(int $tenantId, ?int $employeeId, ?string $attendanceDate): ?int
    {
        if ($employeeId === null || $attendanceDate === null) {
            return null;
        }
        $record = $this->attendance->findForEmployeeDateInTenant($tenantId, $employeeId, $attendanceDate);
        $minutes = (int) ($record?->overtime_minutes ?? 0);

        return $minutes > 0 ? $minutes : null;
    }

    private function normalizeDate(?string $attendanceDate): ?string
    {
        if ($attendanceDate === null || $attendanceDate === '') {
            return null;
        }

        return $attendanceDate;
    }
}
