<?php

use App\Models\Person\Person;
use App\Models\Person\PersonPhone;
use App\Services\Contact\PhoneSelector;

it('selects validated mobile first', function () {
    $person = Person::factory()->create();
    // Non-mobile validated
    PersonPhone::factory()->for($person, 'person')->landline()->validated()->create();
    // Mobile not validated
    PersonPhone::factory()->for($person, 'person')->mobile()->notValidated()->create();
    // Mobile validated (should win)
    $best = PersonPhone::factory()->for($person, 'person')->mobile()->validated()->create();

    $selector = new PhoneSelector;
    $result = $selector->selectForPerson($person->fresh('phones'));

    expect($result['phone'])->not->toBeNull();
    expect($result['phone']->id)->toBe($best->id);
    expect($result['reason'])->toBeNull();
});

it('falls back to validated any type then mobile', function () {
    $person = Person::factory()->create();
    $validatedAny = PersonPhone::factory()->for($person, 'person')->landline()->validated()->create();
    $mobile = PersonPhone::factory()->for($person, 'person')->mobile()->notValidated()->create();

    $selector = new PhoneSelector;
    $result = $selector->selectForPerson($person->fresh('phones'));

    expect($result['phone']->id)->toBe($validatedAny->id);
});

it('returns first active when no better option', function () {
    $person = Person::factory()->create();
    $first = PersonPhone::factory()->for($person, 'person')->landline()->notValidated()->create();
    PersonPhone::factory()->for($person, 'person')->landline()->notValidated()->create();

    $selector = new PhoneSelector;
    $result = $selector->selectForPerson($person->fresh('phones'));

    expect($result['phone']->id)->toBe($first->id);
});

it('returns reason when no phones', function () {
    $person = Person::factory()->create();
    $selector = new PhoneSelector;
    $result = $selector->selectForPerson($person->fresh('phones'));

    expect($result['phone'])->toBeNull();
    expect($result['reason'])->toBe('no_active_phones');
});
