<?php

declare(strict_types=1);

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

/**
 * Создаёт SaaS-level очередь яруса 3 резерва канала миграции проектов.
 *
 * Spec: docs/superpowers/specs/2026-05-19-supplier-project-channel-failover-design.md §4.5
 *
 * Без tenant_id / RLS (как supplier_csv_reconcile_log) — доступ только SaaS-admin.
 */
return new class extends Migration
{
    public function up(): void
    {
        // Guard: после migrate:fresh schema.sql даёт таблицу первой. Idempotent.
        $exists = DB::selectOne(
            "SELECT to_regclass('public.supplier_manual_sync_queue') AS r"
        );
        if ($exists !== null && $exists->r !== null) {
            return;
        }

        // unprepared — multi-statement (PG prepared statements не разрешают `;`).
        DB::unprepared(<<<'SQL'
            CREATE TABLE supplier_manual_sync_queue (
                id BIGSERIAL PRIMARY KEY,
                project_id BIGINT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
                platform VARCHAR(8) NOT NULL,
                operation VARCHAR(16) NOT NULL,
                external_id VARCHAR(64),
                payload_snapshot JSONB NOT NULL,
                failure_reason VARCHAR(64) NOT NULL,
                status VARCHAR(16) NOT NULL DEFAULT 'pending',
                resolved_by_user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
                created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                resolved_at TIMESTAMPTZ,
                CONSTRAINT chk_smsq_platform CHECK (platform IN ('B1', 'B2', 'B3')),
                CONSTRAINT chk_smsq_operation CHECK (operation IN ('create', 'update')),
                CONSTRAINT chk_smsq_status CHECK (status IN ('pending', 'resolved', 'cancelled'))
            );

            CREATE INDEX idx_smsq_status_created ON supplier_manual_sync_queue (status, created_at DESC);
            CREATE INDEX idx_smsq_project ON supplier_manual_sync_queue (project_id);
        SQL);
    }

    public function down(): void
    {
        DB::statement('DROP TABLE IF EXISTS supplier_manual_sync_queue');
    }
};
