<?php

declare(strict_types=1);

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

return new class extends Migration
{
    public function up(): void
    {
        $conn = DB::connection('pgsql_supplier');

        // Guard: only run if webhook_log exists (на проде после legacy-webhook-removal
        // таблицы нет — миграция становится no-op).
        if (! $conn->getSchemaBuilder()->hasTable('webhook_log')) {
            return;
        }

        $sql = (string) file_get_contents(
            base_path('/../db/migrations/2026_05_22_002_webhook_log_supplier_columns.sql')
        );

        $conn->unprepared($sql);
    }

    public function down(): void
    {
        $conn = DB::connection('pgsql_supplier');

        if (! $conn->getSchemaBuilder()->hasTable('webhook_log')) {
            return;
        }

        $conn->unprepared(<<<'SQL'
            ALTER TABLE webhook_log
                DROP COLUMN IF EXISTS source,
                DROP COLUMN IF EXISTS status,
                DROP COLUMN IF EXISTS lead_id,
                DROP COLUMN IF EXISTS ip_address,
                DROP COLUMN IF EXISTS created_at;

            DROP INDEX IF EXISTS idx_webhook_log_status;

            -- Note: tenant_id NOT NULL constraint is NOT restored to avoid data loss.
        SQL);
    }
};
