<?php

namespace App\Console\Commands;

use App\Models\AttendancePunch;
use App\Services\Biometric\ZktecoPunchIngestService;
use Illuminate\Console\Command;

class ReprocessZktecoPendingPunches extends Command
{
    protected $signature = 'zkteco:reprocess-pending {--limit=500 : Max punches to process}';

    protected $description = 'Reprocess pending/error ZKTeco attendance punches synchronously';

    public function handle(ZktecoPunchIngestService $ingestService): int
    {
        $limit = max(1, (int) $this->option('limit'));

        $ids = AttendancePunch::withoutGlobalScopes()
            ->whereIn('status', [
                AttendancePunch::STATUS_PENDING,
                AttendancePunch::STATUS_ERROR,
                AttendancePunch::STATUS_IGNORED,
            ])
            ->orderBy('punch_datetime')
            ->orderBy('id')
            ->limit($limit)
            ->pluck('id');

        if ($ids->isEmpty()) {
            $this->info('No pending/error punches found.');

            return self::SUCCESS;
        }

        $this->info('Reprocessing '.$ids->count().' punch(es)...');

        foreach ($ids as $id) {
            $ingestService->applyPunch((int) $id);
            $punch = AttendancePunch::withoutGlobalScopes()->find($id);
            $this->line("#{$id} → ".($punch?->status ?? 'missing').($punch?->error_message ? ' ('.$punch->error_message.')' : ''));
        }

        $this->info('Done.');

        return self::SUCCESS;
    }
}
