<?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_03_sales_pos_billing.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('traspasos_caja');
        Schema::dropIfExists('cierres_caja');
        Schema::dropIfExists('movimientos_caja');
        Schema::dropIfExists('devoluciones');
        Schema::dropIfExists('factura_detalles');
        Schema::dropIfExists('facturas');
        Schema::dropIfExists('venta_pagos');
        Schema::dropIfExists('venta_detalles');
        Schema::dropIfExists('ventas');
        Schema::dropIfExists('aperturas_caja');
        Schema::dropIfExists('cajas');
        Schema::dropIfExists('clientes');
        DB::statement('SET FOREIGN_KEY_CHECKS=1');
    }
};
