<?php

namespace App\Listeners;

use App\Models\Dialler\AgentStatus;
use App\Services\Dialler\AgentStatusService;
use Illuminate\Auth\Events\Logout;

class SetAgentOfflineOnLogout
{
    public function __construct(private readonly AgentStatusService $agentStatus) {}

    public function handle(Logout $event): void
    {
        if (! $event->user) {
            return;
        }

        // Route through the service so the open interval is closed and an
        // offline interval is opened (an agent may have a snapshot per solicitor).
        AgentStatus::query()
            ->where('agent_id', $event->user->id)
            ->where('status', '!=', 'offline')
            ->get()
            ->each(fn (AgentStatus $snapshot) => $this->agentStatus->transitionTo(
                $snapshot->solicitor_id,
                $snapshot->agent_id,
                'offline',
                ['source' => 'logout'],
            ));
    }
}
