<?php

namespace App\Console\Commands;

use App\Services\Biometric\StaleOpenSessionCleaner;
use Carbon\Carbon;
use Illuminate\Console\Command;

class CloseStaleBiometricOpenSessions extends Command
{
    protected $signature = 'zkteco:close-stale-sessions
                            {--hours= : Max open-session age in hours (default: config zkteco.open_session_max_age_hours)}
                            {--company_id= : Limit to one company}
                            {--before= : Also close opens with attendance date before Y-m-d}
                            {--dry-run : Show how many would close without writing}';

    protected $description = 'Close stale open WorkDuration sessions so biometric Both-mode only toggles same-day/window attendance';

    public function handle(StaleOpenSessionCleaner $cleaner): int
    {
        $hours = $this->option('hours');
        $companyId = $this->option('company_id');
        $before = $this->option('before');
        $dryRun = (bool) $this->option('dry-run');

        $summary = $cleaner->closeStale(
            companyId: $companyId !== null && $companyId !== '' ? (int) $companyId : null,
            maxAgeHours: $hours !== null && $hours !== '' ? (int) $hours : null,
            beforeDate: $before ? Carbon::createFromFormat('Y-m-d', $before)->startOfDay() : null,
            dryRun: $dryRun
        );

        $verb = $dryRun ? 'Would close' : 'Closed';
        $this->info(sprintf(
            '%s %d stale open session(s) (scanned %d, max_age_hours=%d)%s.',
            $verb,
            $summary['closed'],
            $summary['scanned'],
            $summary['max_age_hours'],
            $dryRun ? ' [dry-run]' : ''
        ));

        return self::SUCCESS;
    }
}
