<?php

namespace App\Modules\HR\Attendance\Services;

use App\Modules\HR\Attendance\Services\ExceptionDetection\DuplicatePunchExceptionRule;
use App\Modules\HR\Attendance\Services\ExceptionDetection\ExcessiveOvertimeExceptionRule;
use App\Modules\HR\Attendance\Services\ExceptionDetection\MissingCheckoutExceptionRule;
use App\Modules\HR\Attendance\Services\ExceptionDetection\OutsideShiftExceptionRule;
use App\Modules\HR\Attendance\Services\ExceptionDetection\OverlappingAttendanceExceptionRule;
use App\Modules\HR\Attendance\Services\ExceptionDetection\SuspiciousAttendanceExceptionRule;
use Carbon\CarbonImmutable;

class AttendanceExceptionDetector
{
    public function __construct(
        private readonly MissingCheckoutExceptionRule $missingCheckout,
        private readonly ExcessiveOvertimeExceptionRule $excessiveOvertime,
        private readonly OutsideShiftExceptionRule $outsideShift,
        private readonly SuspiciousAttendanceExceptionRule $suspicious,
        private readonly OverlappingAttendanceExceptionRule $overlapping,
        private readonly DuplicatePunchExceptionRule $duplicatePunch,
    ) {}

    /**
     * Scan attendance data for a tenant and persist deduplicated exceptions.
     */
    public function detectForTenant(int $tenantId, string $fromYmd, string $toYmd): int
    {
        $from = CarbonImmutable::parse($fromYmd)->startOfDay();
        $to = CarbonImmutable::parse($toYmd)->startOfDay();

        $n = 0;
        $n += $this->missingCheckout->run($tenantId, $from, $to);
        $n += $this->excessiveOvertime->run($tenantId, $from, $to);
        $n += $this->outsideShift->run($tenantId, $from, $to);
        $n += $this->suspicious->run($tenantId, $from, $to);
        $n += $this->overlapping->run($tenantId, $from, $to);
        $n += $this->duplicatePunch->run($tenantId, $from, $to);

        return $n;
    }
}
