<?php

namespace App\Actions\Communications;

use App\Models\User\User;
use Twilio\Jwt\AccessToken;
use Twilio\Jwt\Grants\VoiceGrant;

class GenerateVoiceTokenAction
{
    public function handle(User $user): array
    {
        $identity = 'agent_' . $user->id;

        $accountSid = config('services.twilio.sid');
        $apiKey = config('services.twilio.api_key');
        $apiSecret = config('services.twilio.api_secret');
        $twimlAppSid = config('services.twilio.twiml_app_sid');

        $tokenTtl = config('services.twilio.token_ttl', 3600);

        $accessToken = new AccessToken(
            $accountSid,
            $apiKey,
            $apiSecret,
            $tokenTtl,
            $identity
        );

        $voiceGrant = new VoiceGrant();
        $voiceGrant->setOutgoingApplicationSid($twimlAppSid);
        $voiceGrant->setIncomingAllow(true);

        $accessToken->addGrant($voiceGrant);

        return [
            'identity' => $identity,
            'token' => $accessToken->toJWT(),
            'expires_in' => $tokenTtl,
        ];
    }
}