<?php

namespace App\Components\Dialler;

use App\Services\TwilioService;
use Illuminate\Database\Eloquent\Model;
use Livewire\Component;

class InteractionTimeline extends Component {
    public Model $model;

    public function initiateCall(TwilioService $twilioService) {
        $agent = auth()->user();

        try {
            // Trigger the service, passing the polymorphic model
            $twilioService->initiateOutboundCall($agent, $this->model);

            session()->flash('success', 'Call initiated! Your device will ring shortly.');
        } catch (\Exception $e) {
            session()->flash('error', 'Failed to initiate call: ' . $e->getMessage() . " " . $e->getTraceAsString());
        }
    }

    public function render() {
        $history = $this->model->interactions()
            ->with('agent')
            ->orderBy('timestamp', 'desc')->get();

        return view('components.dialler.interaction-timeline', [
            'history' => $history
        ]);
    }
}
