<?php

namespace App\Console\Commands;

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

class CleanupSLAMigrations extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sla:cleanup-migrations';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Remove SLA Tracking extension migration records from migrations table';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Cleaning up SLA Tracking migration records...');

        // Delete all migration records for SLA Tracking extension
        $deleted = DB::table('migrations')
            ->where('migration', 'like', '%_add_sla_%')
            ->orWhere('migration', 'like', '%_create_sla_%')
            ->delete();

        $this->info("Deleted {$deleted} SLA migration record(s) from migrations table.");

        // Also delete the cleanup migration record so it can be run again if needed
        $cleanupDeleted = DB::table('migrations')
            ->where('migration', 'like', '%_remove_sla_fields_from_tickets')
            ->delete();

        if ($cleanupDeleted > 0) {
            $this->info("Deleted {$cleanupDeleted} cleanup migration record(s).");
        }

        $this->newLine();
        $this->info('✓ SLA migration cleanup complete!');
        $this->info('You can now reinstall the SLA Tracking extension and its migrations will run fresh.');

        return Command::SUCCESS;
    }
}
