<?php

namespace App\Modules\HR\Attendance\Services;

use App\Models\User;
use App\Modules\HR\Attendance\Notifications\MissingCheckoutReminderNotification;
use App\Modules\HR\Attendance\Repositories\AttendanceRecordRepository;
use App\Modules\HR\Attendance\Repositories\AttendanceReminderRepository;

class MissingCheckoutReminderService
{
    public function __construct(
        private readonly AttendanceRecordRepository $records,
        private readonly AttendanceReminderRepository $reminders,
    ) {}

    public function remindTenant(int $tenantId, string $beforeDate): int
    {
        $sent = 0;
        foreach ($this->records->cursorOpenBeforeDateForTenant($tenantId, $beforeDate) as $record) {
            $user = $record->employee?->user;
            $record = $this->records->update($record, ['missing_checkout' => true]);
            if (! $user instanceof User || ! $user->is_active) {
                continue;
            }
            if ($this->reminders->missingCheckoutReminderExists($user, (int) $record->id)) {
                continue;
            }
            $user->notify(new MissingCheckoutReminderNotification($record));
            $sent++;
        }

        return $sent;
    }
}
