<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        $sql = file_get_contents(base_path('database/schema/legacy/batch_05_saas_support_integrations.sql'));

        if (! is_string($sql) || trim($sql) === '') {
            return;
        }

        $normalized = preg_replace('/^\s*--.*$/m', '', $sql) ?: $sql;

        $statements = array_filter(
            array_map('trim', preg_split('/;\s*\n/', $normalized) ?: []),
            static fn (string $statement): bool => $statement !== ''
        );

        foreach ($statements as $statement) {
            DB::unprepared($statement.';');
        }
    }

    public function down(): void
    {
        DB::statement('SET FOREIGN_KEY_CHECKS=0');
        Schema::dropIfExists('logs_actividad');
        Schema::dropIfExists('notificacion_vistas');
        Schema::dropIfExists('soporte_ticket_eventos');
        Schema::dropIfExists('soporte_tickets');
        Schema::dropIfExists('ai_help_messages');
        Schema::dropIfExists('ai_help_sessions');
        Schema::dropIfExists('whatsapp_meta_templates');
        Schema::dropIfExists('saas_checkout_intents');
        Schema::dropIfExists('avisos_cobro_suscripcion');
        Schema::dropIfExists('pagos_suscripcion');
        DB::statement('SET FOREIGN_KEY_CHECKS=1');
    }
};
