<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class PruneStaleDispatchJobs extends Command
{
    protected $signature = 'queue:prune-stale-dispatch {--hours=24 : Only remove known dispatch/sync jobs older than this many hours}';
    protected $description = 'Remove stale scheduler dispatch jobs without touching customer, payment, or device-write jobs';

    public function handle(): int
    {
        $hours = max(1, min(24 * 30, (int) $this->option('hours')));
        $classes = [
            'App\\Jobs\\DispatchScheduledSmsJob',
            'App\\Jobs\\SyncMikrotikRouterDataJob',
            'App\\Jobs\\TestMikrotikConnectionJob',
            'App\\Jobs\\SyncOltGatewayJob',
        ];

        $query = DB::table('jobs')->where('created_at', '<', now()->subHours($hours)->timestamp);
        $query->whereIn(
            DB::raw("JSON_UNQUOTE(JSON_EXTRACT(payload, '$.displayName'))"),
            $classes
        );

        $count = (clone $query)->count();
        if ($count === 0) {
            $this->info('No stale dispatch jobs found.');
            return self::SUCCESS;
        }

        $query->delete();
        $this->info("Removed {$count} stale dispatch/sync jobs older than {$hours} hour(s).");
        $this->line('No customer, payment, billing, MikroTik enable/disable, or OLT write job is included in this command.');

        return self::SUCCESS;
    }
}
