<?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 Carbon\CarbonImmutable;

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

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

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