<?php

namespace App\Console\Commands;

use App\Models\FingerprintMachine;
use App\Services\Fingerprint\FingerprintDeviceManager;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class SyncFingerprintTimeCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fingerprint:sync-time';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sinkronisasi jam internal seluruh mesin fingerprint online dengan waktu server (Asia/Jakarta).';

    /**
     * Execute the console command.
     */
    public function handle(FingerprintDeviceManager $deviceManager): int
    {
        $this->info('Memulai sinkronisasi waktu mesin fingerprint...');

        $machines = FingerprintMachine::all();
        $successCount = 0;
        $failedCount = 0;

        foreach ($machines as $machine) {
            try {
                $provider = $deviceManager->make($machine);
                $res = $provider->setDeviceTime($machine);

                if ($res['success']) {
                    $successCount++;
                    $this->info("[OK] Berhasil menyinkronkan waktu untuk mesin '{$machine->name}'.");
                } else {
                    $failedCount++;
                    $this->error("[GAGAL] Gagal menyinkronkan waktu untuk mesin '{$machine->name}': " . $res['message']);
                }
            } catch (\Exception $e) {
                $failedCount++;
                $this->error("[ERROR] Gagal memproses mesin '{$machine->name}': " . $e->getMessage());
                Log::error("Error in fingerprint:sync-time command for machine {$machine->id}: " . $e->getMessage());
            }
        }

        $this->info("Penyelarasan Waktu Selesai: {$successCount} mesin disinkronkan, {$failedCount} gagal.");

        return Command::SUCCESS;
    }
}
