<?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();

        // Agent availability. Users with cross-workspace permission see every
        // agent and which workspace they are in; everyone else sees only the
        // agents currently in the workspace they are viewing.
        $canViewAllWorkspaces = (bool) auth()->user()?->can('communications.agents.view.all_workspaces');

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

        if ($canViewAllWorkspaces) {
            $agentStatusQuery->with('solicitor:id,name');
        } else {
            $agentStatusQuery->where('solicitor_id', $solicitorId);
        }

        $agentStatuses = $agentStatusQuery->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();

        // The top stat cards always reflect the workspace being viewed, even when
        // the availability table is showing every workspace.
        $workspaceStatuses = $canViewAllWorkspaces
            ? AgentStatus::query()->where('solicitor_id', $solicitorId)->get(['status'])
            : $agentStatuses;

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

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