<?php

namespace App\Services\Attendance;

use App\Models\AttendanceLog;
use Carbon\CarbonInterface;
use Illuminate\Support\Collection;

class AttendanceEngine
{
    public function calculateDailySummary(int $tenantId, CarbonInterface $date): array
    {
        $logs = AttendanceLog::query()
            ->where('tenant_id', $tenantId)
            ->whereDate('punched_at', $date)
            ->orderBy('punched_at')
            ->get()
            ->groupBy('employee_id');

        return $logs->map(fn (Collection $employeeLogs) => $this->summarizeEmployeeDay($employeeLogs))->values()->all();
    }

    private function summarizeEmployeeDay(Collection $logs): array
    {
        $first = $logs->first();
        $last = $logs->last();

        return [
            'employee_id' => $first->employee_id,
            'first_in' => $first->punched_at,
            'last_out' => $last->punched_at,
            'punch_count' => $logs->count(),
            'status' => $logs->isEmpty() ? 'absent' : 'present',
            'missing_punch' => $logs->count() % 2 !== 0,
        ];
    }
}
