<?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_04_purchasing.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('pagos_compra');
        Schema::dropIfExists('compra_detalles');
        Schema::dropIfExists('compras');
        Schema::dropIfExists('recepcion_compra_detalles');
        Schema::dropIfExists('recepciones_compra');
        Schema::dropIfExists('orden_compra_detalles');
        Schema::dropIfExists('ordenes_compra');
        DB::statement('SET FOREIGN_KEY_CHECKS=1');
    }
};
