<?php

declare(strict_types=1);

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

/**
 * Бэкофилл pivot project_supplier_links из legacy supplier_b{1,2,3}_project_id (v8.26).
 *
 * Для каждого ненулевого слота → строка pivot (subject_code=NULL: legacy-записи без
 * субъекта). Идемпотентно — ON CONFLICT DO NOTHING по uq_psl_project_supplier.
 */
return new class extends Migration
{
    public function up(): void
    {
        foreach (['B1' => 'supplier_b1_project_id', 'B2' => 'supplier_b2_project_id', 'B3' => 'supplier_b3_project_id'] as $platform => $col) {
            DB::statement(
                'INSERT INTO project_supplier_links (project_id, supplier_project_id, platform, subject_code, created_at) '
                ."SELECT id, {$col}, ?, NULL, NOW() FROM projects WHERE {$col} IS NOT NULL "
                .'ON CONFLICT (project_id, supplier_project_id) DO NOTHING',
                [$platform]
            );
        }
    }

    public function down(): void
    {
        // Бэкофилл-данные не откатываем точечно (pivot живёт дальше); no-op.
    }
};
