<?php

namespace App\Modules\HR\Attendance\Services;

use App\Modules\HR\Attendance\Models\BiometricLog;
use Illuminate\Support\Collection;

final class BiometricAttendanceDayClusterer
{
    private const MAX_GAP_HOURS = 16;

    /**
     * @param  Collection<int, BiometricLog>  $logsSameFingerprint
     * @return Collection<int, Collection<int, BiometricLog>>
     */
    public function clusterByTimeGaps(Collection $logsSameFingerprint): Collection
    {
        $sorted = $logsSameFingerprint->sortBy(fn (BiometricLog $l) => $l->punch_time->timestamp)->values();
        $clusters = collect();
        $current = collect();
        foreach ($sorted as $log) {
            if ($current->isEmpty()) {
                $current->push($log);

                continue;
            }
            /** @var BiometricLog $last */
            $last = $current->last();
            if ($last->punch_time->diffInHours($log->punch_time, false) > self::MAX_GAP_HOURS) {
                $clusters->push($current);
                $current = collect([$log]);
            } else {
                $current->push($log);
            }
        }
        if ($current->isNotEmpty()) {
            $clusters->push($current);
        }

        return $clusters;
    }
}
