<?php

namespace App\Services\Contact;

use App\Enums\PersonPhoneType;
use App\Models\Person\Person;
use App\Models\Person\PersonPhone;

class PhoneSelector
{
    /**
     * Select the best phone for a person following priority rules.
     * Priority:
     * 1) validated mobile
     * 2) validated (any type)
     * 3) mobile (any validation)
     * 4) first active phone
     *
     * Returns an array shape: ['phone' => ?PersonPhone, 'reason' => ?string]
     */
    public function selectForPerson(Person $person): array
    {
        // Load active phones only (Person relation already filters active=1)
        $phones = $person->phones;

        if ($phones->isEmpty()) {
            return ['phone' => null, 'reason' => 'no_active_phones'];
        }

        // 1) validated mobile
        $phone = $phones->first(function (PersonPhone $p) {
            return ($p->validated === true) && ($p->phone_type === PersonPhoneType::Mobile);
        });
        if ($phone) {
            return ['phone' => $phone, 'reason' => null];
        }

        // 2) validated (any type)
        $phone = $phones->first(fn (PersonPhone $p) => $p->validated === true);
        if ($phone) {
            return ['phone' => $phone, 'reason' => null];
        }

        // 3) mobile (any validation)
        $phone = $phones->first(fn (PersonPhone $p) => $p->phone_type === PersonPhoneType::Mobile);
        if ($phone) {
            return ['phone' => $phone, 'reason' => null];
        }

        // 4) first active
        return ['phone' => $phones->first(), 'reason' => null];
    }
}
