<?php

namespace App\Console\Commands;

use App\Models\GarmentType;
use Illuminate\Console\Command;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Schema;

class VerifyD6PostMigrationCommand extends Command
{
    protected $signature = 'laundry:verify-d6-post-migration {--fail-on-warning : Sale con código 1 si detecta advertencias}';

    protected $description = 'Checklist técnico D6: estructura garment_types (sin precios/cobro en prenda) y compatibilidad post-migración.';

    public function handle(): int
    {
        $warnings = [];

        $this->info('Verificando D6 post-migración...');

        try {
            return $this->runChecks($warnings);
        } catch (QueryException $e) {
            $this->warn('No fue posible conectar a la base de datos para el checklist D6.');
            $this->warn('Detalle: '.$e->getMessage());

            return self::SUCCESS;
        }
    }

    /**
     * @param  array<int, string>  $warnings
     */
    private function runChecks(array &$warnings): int
    {
        foreach (['code', 'name', 'sort_order', 'default_load_type_id', 'is_active'] as $col) {
            $ok = Schema::hasColumn('garment_types', $col);
            $this->line(sprintf('- Columna garment_types.%s: %s', $col, $ok ? 'OK' : 'FALTA'));
            if (! $ok) {
                $warnings[] = "Falta columna garment_types.{$col}";
            }
        }

        foreach (['default_billing_mode', 'default_unit_price_lavado', 'default_unit_price_planchado', 'default_unit_price_completo'] as $legacy) {
            if (Schema::hasColumn('garment_types', $legacy)) {
                $this->line(sprintf('- Columna legada garment_types.%s: aún presente (ejecute php artisan migrate)', $legacy));
                $warnings[] = "Columna legada garment_types.{$legacy} aún existe.";
            }
        }

        if (Schema::hasColumn('garment_types', 'default_load_type_id')) {
            $nullLoads = GarmentType::query()->whereNull('default_load_type_id')->count();
            $this->line(sprintf('- Prendas sin default_load_type_id (permitido por fallback): %d', $nullLoads));
        }

        if ($warnings === []) {
            $this->info('D6 OK: estructura y defaults en estado compatible.');

            return self::SUCCESS;
        }

        $this->warn('D6 con advertencias:');
        foreach ($warnings as $warning) {
            $this->warn("  - {$warning}");
        }

        return $this->option('fail-on-warning') ? self::FAILURE : self::SUCCESS;
    }
}
