<?php

declare(strict_types=1);

use App\Models\Tenant;
use App\Models\User;
use App\Services\Requisites\RequisitesService;
use Illuminate\Foundation\Testing\DatabaseTransactions;

uses(DatabaseTransactions::class);

/** @return array<string,mixed> */
function validProjectPayload(): array
{
    return [
        'name' => 'Тестовый проект',
        'signal_type' => 'site',
        'signal_identifier' => 'example.com',
        'daily_limit_target' => 5,
        'regions' => [],
        'delivery_days_mask' => 127,
    ];
}

it('blocks first project when requisites missing', function () {
    $tenant = Tenant::factory()->create();
    $this->actingAs(User::factory()->create(['tenant_id' => $tenant->id]));

    $this->postJson('/api/projects', validProjectPayload())
        ->assertStatus(422)
        ->assertJson(['error' => 'requisites_required']);
});

it('allows first project once light requisites filled', function () {
    $tenant = Tenant::factory()->create();
    $this->actingAs(User::factory()->create(['tenant_id' => $tenant->id]));
    (new RequisitesService)->upsert($tenant, [
        'subject_type' => 'individual', 'contact_name' => 'A', 'contact_phone' => '9151234567',
    ]);

    $this->postJson('/api/projects', validProjectPayload())->assertCreated();
});

it('does not gate the second project', function () {
    $tenant = Tenant::factory()->create();
    $this->actingAs(User::factory()->create(['tenant_id' => $tenant->id]));
    (new RequisitesService)->upsert($tenant, [
        'subject_type' => 'individual', 'contact_name' => 'A', 'contact_phone' => '9151234567',
    ]);

    $this->postJson('/api/projects', validProjectPayload())->assertCreated();

    $payload = validProjectPayload();
    $payload['name'] = 'Второй проект';
    $payload['signal_identifier'] = 'example2.com';
    $this->postJson('/api/projects', $payload)->assertCreated();
});
