<?php

declare(strict_types=1);

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

/**
 * Phase 3 — DIRECT supplier row (used by LedgerService::resolveSupplierId
 * fallback for platform='DIRECT'). cost_rub matches B1 (same supplier,
 * different routing).
 *
 * Spec: docs/superpowers/specs/2026-05-25-supplier-webhook-reliability-design.md §3 Phase 3
 */
return new class extends Migration
{
    public function up(): void
    {
        $b1 = DB::table('suppliers')->where('code', 'b1')->first();
        if ($b1 === null) {
            // Если B1 нет — significant prod drift, не должно произойти.
            // Создаём с дефолтным cost_rub=1.00 (как на prod 25.05.2026).
            $costRub = '1.00';
        } else {
            $costRub = (string) $b1->cost_rub;
        }

        // Используем raw SQL чтобы корректно сериализовать PG-array для accepts_types.
        DB::insert(
            "INSERT INTO suppliers (code, name, accepts_types, cost_rub, channel, is_active, sort_order, created_at)
             VALUES (?, ?, ARRAY['websites','calls','sms'], ?, ?, true, 4, NOW())
             ON CONFLICT (code) DO NOTHING",
            [
                'direct',
                'DIRECT — Прямые проекты',
                $costRub,
                'sites', // принимает любые сигналы; channel='sites' допустим в suppliers_channel_check
            ]
        );
    }

    public function down(): void
    {
        DB::table('suppliers')->where('code', 'direct')->delete();
    }
};
