<?php

namespace App\Components\Dialler;

use App\Enum\Communication\CommunicationStatus;
use App\Models\Communication\Communication;
use App\Models\Communication\Voicemail;
use App\Models\Dialler\AgentStatus;
use App\Models\Solicitor\Solicitor;
use Livewire\Component;

class Dashboard extends Component
{
    public function markListened(int $voicemailId): void
    {
        $solicitorId = app(Solicitor::class)?->id;

        Voicemail::where('solicitor_id', $solicitorId)
            ->findOrFail($voicemailId)
            ->update(['is_listened' => true]);
    }

    public function render()
    {
        $solicitorId = app(Solicitor::class)?->id;

        $activeCalls = Communication::query()
            ->with(['call', 'agent:id,name_first,name_last', 'communicable'])
            ->where('solicitor_id', $solicitorId)
            ->whereIn('status', [
                CommunicationStatus::InProgress->value,
                CommunicationStatus::Ringing->value,
            ])
            ->latest('started_at')
            ->get();

        $agentStatuses = AgentStatus::query()
            ->with('agent:id,name_first,name_last')
            ->where('solicitor_id', $solicitorId)
            ->orderByRaw("FIELD(status, 'available', 'busy', 'wrap_up', 'do_not_disturb', 'offline')")
            ->get();

        $missedCalls = Communication::query()
            ->with(['call', 'communicable'])
            ->where('solicitor_id', $solicitorId)
            ->where('status', CommunicationStatus::Missed->value)
            ->whereDate('created_at', today())
            ->latest('started_at')
            ->get();

        $voicemails = Voicemail::query()
            ->with([
                'communication.communicable',
                'recording',
                'assignedAgent:id,name_first,name_last',
            ])
            ->where('solicitor_id', $solicitorId)
            ->where('is_listened', false)
            ->latest('received_at')
            ->get();

        $availableCount = $agentStatuses->where('status', 'available')->count();

        return view('components.dialler.dashboard', compact(
            'activeCalls',
            'agentStatuses',
            'missedCalls',
            'voicemails',
            'availableCount',
        ));
    }
}
