<?php

namespace App\Modules\HR\EmployeeSelfService\Services;

use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\HR\Attendance\Repositories\AttendanceRecordRepository;
use App\Modules\HR\Attendance\Services\AttendanceHistoryWindowService;
use App\Modules\HR\Employees\Models\Employee;
use App\Modules\HR\EmployeeSelfService\Requests\MeAttendanceIndexRequest;
use App\Modules\HR\Shifts\Services\ShiftResolutionService;
use Carbon\CarbonImmutable;

class SelfAttendancePageService
{
    public function __construct(
        private readonly AttendanceRecordRepository $records,
        private readonly AttendanceHistoryWindowService $historyWindow,
        private readonly ShiftResolutionService $shifts,
    ) {}

    /**
     * @return array<string, mixed>
     */
    public function data(Tenant $tenant, Employee $employee, MeAttendanceIndexRequest $request): array
    {
        $timezone = $tenant->timezone ?: config('app.timezone');
        $now = CarbonImmutable::now($timezone);
        $attendanceDate = $this->shifts->resolveAttendanceDateForPunch($employee, $now);
        $floor = $this->historyWindow->earliestReportDate($tenant);
        $from = $request->fromOrDefault($floor?->toDateString() ?? now()->subMonth()->toDateString());
        $to = $request->toOrDefault($now->toDateString());

        return [
            'paginator' => $this->records->paginateForEmployee(
                (int) $tenant->id,
                (int) $employee->id,
                $from,
                $to,
            ),
            'todayRecord' => $this->records->findForEmployeeDateInTenant(
                (int) $tenant->id,
                (int) $employee->id,
                $attendanceDate,
            ),
            'missingCheckoutRecords' => $this->records->unresolvedMissingCheckouts(
                (int) $tenant->id,
                (int) $employee->id,
            ),
            'from' => $from,
            'to' => $to,
        ];
    }
}
