<?php

declare(strict_types=1);

use App\Jobs\Supplier\DeleteSupplierProjectJob;
use App\Jobs\Supplier\SyncSupplierProjectsJob;
use App\Models\Project;
use App\Models\SupplierProject;
use App\Models\Tenant;
use App\Services\Supplier\SupplierPortalClient;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\DB;
use Tests\Concerns\SharesSupplierPdo;

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

it('deletes donor at supplier when no consumers remain', function (): void {
    $sp = SupplierProject::query()->create([
        'platform' => 'B1', 'signal_type' => 'call', 'unique_key' => '79991110000',
        'supplier_external_id' => '555', 'current_limit' => 1,
    ]);

    $mock = Mockery::mock(SupplierPortalClient::class);
    $mock->shouldReceive('deleteProject')->once()->with(555);
    app()->instance(SupplierPortalClient::class, $mock);

    (new DeleteSupplierProjectJob([$sp->id]))->handle(app(SupplierPortalClient::class));

    expect(SupplierProject::find($sp->id))->toBeNull();
});

it('does NOT delete donor at supplier when other consumers remain; re-syncs', function (): void {
    Bus::fake([SyncSupplierProjectsJob::class]);

    $tenant = Tenant::factory()->create(['balance_leads' => 100]);
    $sp = SupplierProject::query()->create([
        'platform' => 'B1', 'signal_type' => 'call', 'unique_key' => '79991110001',
        'supplier_external_id' => '556', 'current_limit' => 1,
    ]);
    $other = Project::factory()->create(['tenant_id' => $tenant->id]);

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

    $mock = Mockery::mock(SupplierPortalClient::class);
    $mock->shouldNotReceive('deleteProject');
    app()->instance(SupplierPortalClient::class, $mock);

    (new DeleteSupplierProjectJob([$sp->id]))->handle(app(SupplierPortalClient::class));

    expect(SupplierProject::find($sp->id))->not->toBeNull();
    Bus::assertDispatched(SyncSupplierProjectsJob::class);
});
