<?php

declare(strict_types=1);

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

uses(DatabaseTransactions::class);

it('upsert normalizes phone and is idempotent on tenant', function () {
    $tenant = Tenant::factory()->create();
    $svc = new RequisitesService;

    $r1 = $svc->upsert($tenant, [
        'subject_type' => 'individual',
        'contact_name' => 'Иван Иванов',
        'contact_phone' => '8 (915) 123-45-67',
    ]);
    expect($r1->contact_phone)->toBe('+79151234567');

    $r2 = $svc->upsert($tenant, [
        'subject_type' => 'individual',
        'contact_name' => 'Иван Петров',
        'contact_phone' => '9151234567',
    ]);
    expect($r2->id)->toBe($r1->id);                 // одна строка на тенанта
    expect($r2->contact_name)->toBe('Иван Петров');
});

it('sets requisites_completed_at only when bank_account present', function () {
    $tenant = Tenant::factory()->create();
    $svc = new RequisitesService;

    $r = $svc->upsert($tenant, [
        'subject_type' => 'legal_entity', 'contact_name' => 'A', 'contact_phone' => '9151234567',
        'inn' => '7707083893',
    ]);
    expect($r->requisites_completed_at)->toBeNull();

    $r = $svc->upsert($tenant, [
        'subject_type' => 'legal_entity', 'contact_name' => 'A', 'contact_phone' => '9151234567',
        'inn' => '7707083893', 'bank_account' => '40702810900000000001',
    ]);
    expect($r->requisites_completed_at)->not->toBeNull();
});

it('isLightComplete requires inn for legal entity but not individual', function () {
    $svc = new RequisitesService;

    $t1 = Tenant::factory()->create();
    $svc->upsert($t1, ['subject_type' => 'individual', 'contact_name' => 'A', 'contact_phone' => '9151234567']);
    expect($svc->isLightComplete($t1->fresh()))->toBeTrue();

    $t2 = Tenant::factory()->create();
    $svc->upsert($t2, ['subject_type' => 'legal_entity', 'contact_name' => 'A', 'contact_phone' => '9151234567']);
    expect($svc->isLightComplete($t2->fresh()))->toBeFalse(); // нет ИНН

    $svc->upsert($t2, ['subject_type' => 'legal_entity', 'contact_name' => 'A', 'contact_phone' => '9151234567', 'inn' => '7707083893']);
    expect($svc->isLightComplete($t2->fresh()))->toBeTrue();

    $t3 = Tenant::factory()->create();
    expect($svc->isLightComplete($t3))->toBeFalse(); // вообще нет записи
});
