<?php

declare(strict_types=1);

use App\Models\Project;
use App\Models\Tenant;
use App\Models\User;
use App\Services\Supplier\SupplierPortalClient;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Http;
use Tests\Concerns\SharesSupplierPdo;

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

beforeEach(function (): void {
    $this->tenant = Tenant::factory()->create();
    User::factory()->create(['tenant_id' => $this->tenant->id, 'email' => 'info@lkomega.ru']);

    $client = Mockery::mock(SupplierPortalClient::class);
    $client->shouldReceive('listProjects')->andReturn([
        ['id' => '4001', 'src' => 'rt', 'type' => 'calls', 'content' => '79991112233', 'tag' => 'Каранга', 'lim' => '6', 'status' => true, 'regions' => '', 'workdays' => ['1', '2', '3', '4', '5']],
        ['id' => '4002', 'src' => 'bl', 'type' => 'calls', 'content' => '79991112233', 'tag' => 'Каранга', 'lim' => '6', 'status' => true, 'regions' => '', 'workdays' => ['1', '2', '3', '4', '5']],
        ['id' => '4003', 'src' => 'mt', 'type' => 'calls', 'content' => '79991112233', 'tag' => 'Каранга', 'lim' => '6', 'status' => true, 'regions' => '', 'workdays' => ['1', '2', '3', '4', '5']],
    ]);
    $this->app->instance(SupplierPortalClient::class, $client);
});

test('dry-run prints plan and writes nothing', function (): void {
    Http::fake();

    $this->artisan('supplier:import-projects', ['--tenant' => 'info@lkomega.ru'])
        ->assertExitCode(0);

    expect(Project::on('pgsql_supplier')->where('tenant_id', $this->tenant->id)->count())->toBe(0);
    Http::assertNothingSent();
});

test('--commit writes projects', function (): void {
    Http::fake();

    $this->artisan('supplier:import-projects', ['--tenant' => 'info@lkomega.ru', '--commit' => true])
        ->assertExitCode(0);

    expect(Project::on('pgsql_supplier')
        ->where('tenant_id', $this->tenant->id)
        ->where('signal_identifier', '79991112233')->count())->toBe(1);
    Http::assertNothingSent();
});

test('unknown tenant email → non-zero exit, no write', function (): void {
    $this->artisan('supplier:import-projects', ['--tenant' => 'nobody@nowhere.ru', '--commit' => true])
        ->assertExitCode(1);
});
