<?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('creates pivot row linking project to supplier_project', function (): void {
    $project = Project::factory()->create();
    $sp = SupplierProject::query()->create([
        'platform' => 'B1', 'signal_type' => 'site', 'unique_key' => 'link.ru',
        'subject_code' => 82, 'current_limit' => 0, 'sync_status' => 'ok',
    ]);

    DB::table('project_supplier_links')->insert([
        'project_id' => $project->id,
        'supplier_project_id' => $sp->id,
        'platform' => 'B1',
        'subject_code' => 82,
    ]);

    expect(DB::table('project_supplier_links')
        ->where('project_id', $project->id)->where('supplier_project_id', $sp->id)->exists())->toBeTrue();
});

it('cascades pivot deletion when supplier_project is deleted', function (): void {
    $project = Project::factory()->create();
    $sp = SupplierProject::query()->create([
        'platform' => 'B2', 'signal_type' => 'site', 'unique_key' => 'cascade.ru',
        'subject_code' => 82, 'current_limit' => 0, 'sync_status' => 'ok',
    ]);
    DB::table('project_supplier_links')->insert([
        'project_id' => $project->id, 'supplier_project_id' => $sp->id, 'platform' => 'B2', 'subject_code' => 82,
    ]);

    $sp->delete();

    expect(DB::table('project_supplier_links')->where('supplier_project_id', $sp->id)->exists())->toBeFalse();
});
