<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // Idempotency guard: skip if table already exists (e.g. loaded via schema.sql).
        if (DB::selectOne('SELECT 1 AS ok FROM pg_class WHERE relname = ?', ['supplier_lead_deliveries']) !== null) {
            return;
        }

        $sql = file_get_contents(base_path('../db/migrations/2026_05_23_200_supplier_lead_deliveries.sql'));
        if ($sql === false) {
            throw new RuntimeException('Migration SQL file not found.');
        }
        // Prod: crm_app_user (default pgsql) не имеет CREATE на schema public.
        // Используем pgsql_supplier (crm_supplier_worker, BYPASSRLS, имеет CREATE).
        // На dev pgsql_supplier тоже = postgres superuser → работает идентично.
        DB::connection('pgsql_supplier')->unprepared($sql);
    }

    public function down(): void
    {
        DB::connection('pgsql_supplier')->unprepared('DROP TABLE IF EXISTS supplier_lead_deliveries CASCADE;');
    }
};
