<?php

namespace App\Services\Communications;

/**
 * Builds the Twilio Voice client identity for an agent.
 *
 * The identity is what the browser dialler registers as (via the access token)
 * and what the server targets when it dials `<Client>`. Twilio client
 * registration is scoped to the Twilio *account*, not the TwiML app — so when
 * several environments share one account, an un-namespaced `agent_{id}` causes
 * an incoming call to ring that agent's dialler in *every* environment they are
 * signed into (e.g. staging and live both ringing at once).
 *
 * Prefixing with the environment keeps each environment's registrations in
 * their own namespace. This MUST produce the identical string everywhere the
 * identity is minted or dialled, or calls will not connect.
 */
final class TwilioClientIdentity
{
    public static function for(int $agentId): string
    {
        return 'agent_' . self::prefix() . '_' . $agentId;
    }

    protected static function prefix(): string
    {
        $prefix = (string) config('services.twilio.client_prefix', 'local');

        // Twilio client identities allow a limited character set; strip
        // anything outside [A-Za-z0-9] so an env value like "local.test"
        // can never produce an invalid or ambiguous identity.
        $prefix = preg_replace('/[^A-Za-z0-9]+/', '', $prefix) ?: 'local';

        return $prefix;
    }
}
