<?php

declare(strict_types=1);

use App\Models\SupplierLead;
use App\Services\Dto\RegionResolution;

it('exposes the source rank ordering dadata>rossvyaz>tag>unknown', function (): void {
    expect(RegionResolution::SOURCE_RANK)->toBe([
        'dadata' => 4, 'rossvyaz' => 3, 'tag' => 2, 'unknown' => 1,
    ]);
});

it('make sets actualSubjectCode equal to subjectCode', function (): void {
    $r = RegionResolution::make(82, 'dadata', operator: 'МТС', qc: 0);

    expect($r->subjectCode)->toBe(82)
        ->and($r->actualSubjectCode)->toBe(82)
        ->and($r->source)->toBe('dadata')
        ->and($r->phoneOperator)->toBe('МТС')
        ->and($r->qc)->toBe(0)
        ->and($r->cacheHit)->toBeFalse()
        ->and($r->rossvyazMatched)->toBeFalse();
});

it('fromTag builds a tag-sourced resolution', function (): void {
    $r = RegionResolution::fromTag(82);

    expect($r->subjectCode)->toBe(82)
        ->and($r->source)->toBe('tag')
        ->and($r->phoneOperator)->toBeNull();
});

it('fromSupplierLead reconstructs a persisted resolution (idempotency)', function (): void {
    $lead = new SupplierLead([
        'resolved_subject_code' => 83,
        'region_source' => 'dadata',
        'dadata_qc' => 0,
        'phone_operator' => 'МегаФон',
    ]);

    $r = RegionResolution::fromSupplierLead($lead);

    expect($r->subjectCode)->toBe(83)
        ->and($r->source)->toBe('dadata')
        ->and($r->phoneOperator)->toBe('МегаФон')
        ->and($r->qc)->toBe(0);
});

it('withCacheHit flips the flag and clears the per-call masked response', function (): void {
    $r = RegionResolution::make(82, 'dadata', operator: 'МТС', qc: 0, dadataMasked: ['phone' => '7916***4567']);

    $hit = $r->withCacheHit(true);

    expect($hit->cacheHit)->toBeTrue()
        ->and($hit->subjectCode)->toBe(82)
        ->and($hit->dadataResponseMasked)->toBeNull();
});

it('forCache strips per-call fields before storing', function (): void {
    $r = RegionResolution::make(82, 'dadata', operator: 'МТС', qc: 0, dadataMasked: ['phone' => 'x'], durationMs: 120);

    $c = $r->forCache();

    expect($c->dadataResponseMasked)->toBeNull()
        ->and($c->durationMs)->toBeNull()
        ->and($c->cacheHit)->toBeFalse()
        ->and($c->subjectCode)->toBe(82)
        ->and($c->phoneOperator)->toBe('МТС');
});
