<?php

namespace App\Services;

use App\Models\Interaction;
use App\Models\Solicitor\Solicitor;
use App\Models\User\User;
use Illuminate\Database\Eloquent\Model;
use Twilio\Rest\Client;

class TwilioService {
    /**
     * Initiates an outbound call without requiring the agent to select a number.
     * * @param User $agent The staff member making the call
     * @param Model $interactable The polymorphic model being called (e.g., Contact, Case, Institution)
     */
    public function initiateOutboundCall(User $agent, Model $interactable) {
        $solicitor = $interactable->solicitor;

        $contactType = $interactable->type ?? 'client';
        $fromNumber = $this->resolveOutboundNumber($solicitor, $contactType);

        $twilio = new Client(
            $solicitor->twilio_subaccount_sid ?? env('TWILIO_SID'),
            $solicitor->twilio_auth_token ?? env('TWILIO_AUTH_TOKEN')
        );

        // 3. Create the initial interaction record polymorphically
        $interaction = Interaction::create([
            'solicitor_id' => $solicitor->id,
            'agent_id' => $agent->id,
            'interactable_id' => $interactable->id,
            'interactable_type' => get_class($interactable),
            'channel' => 'voice',
            'direction' => 'outbound',
            'status' => 'initiated',
            'timestamp' => now()
        ]);

        // 4. Dispatch the call via Twilio API
        // Agents are bridged via their local device/browser or phone
        $call = $twilio->calls->create(
            $interactable->phone_number, // To (Assumes the polymorphic model has a phone_number property)
            $fromNumber, // From (Auto-selected)
            [
                'url' => route('twilio.outbound.bridge', ['agent_id' => $agent->id]), // TwiML to connect agent
                'statusCallback' => route('twilio.status'),
                'statusCallbackEvent' => ['initiated', 'ringing', 'answered', 'completed'],
                'record' => true, // Enforce recording
                'recordingStatusCallback' => route('twilio.recording')
            ]
        );

        // 5. Update record with Twilio Call SID
        $interaction->update(['call_sid' => $call->sid]);

        return $interaction;
    }

    /**
     * Resolves which of the 3 solicitor numbers to use based on the contact.
     */
    private function resolveOutboundNumber(Solicitor $solicitor, string $contactType): string {
        return match ($contactType) {
            'client', 'supporting' => $solicitor->phone_client_line,
            'institution', 'authority', 'respondent' => $solicitor->phone_external_line,
            default => $solicitor->phone_main_inbound,
        };
    }
}