<?php

declare(strict_types=1);

use App\Models\Project;
use App\Models\SupplierProject;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Tests\Concerns\SharesSupplierPdo;

uses(DatabaseTransactions::class, SharesSupplierPdo::class);

it('backfills pivot rows from legacy supplier_b{1,2,3}_project_id slots', function (): void {
    $sp1 = SupplierProject::query()->create([
        'platform' => 'B1', 'signal_type' => 'site', 'unique_key' => 'bf.ru',
        'subject_code' => null, 'current_limit' => 0, 'sync_status' => 'ok',
    ]);
    $sp3 = SupplierProject::query()->create([
        'platform' => 'B3', 'signal_type' => 'site', 'unique_key' => 'bf.ru',
        'subject_code' => null, 'current_limit' => 0, 'sync_status' => 'ok',
    ]);
    $project = Project::factory()->create([
        'supplier_b1_project_id' => $sp1->id,
        'supplier_b3_project_id' => $sp3->id,
    ]);

    // Симулируем «до бэкофилла»: pivot пуст.
    DB::table('project_supplier_links')->where('project_id', $project->id)->delete();

    // Запуск логики бэкофилла повторно (миграция идемпотентна).
    require_once base_path('database/migrations/2026_05_20_104000_backfill_project_supplier_links.php');
    (include base_path('database/migrations/2026_05_20_104000_backfill_project_supplier_links.php'))->up();

    $rows = DB::table('project_supplier_links')->where('project_id', $project->id)->get();
    expect($rows)->toHaveCount(2)
        ->and($rows->pluck('platform')->sort()->values()->all())->toBe(['B1', 'B3']);
});
