<?php

namespace App\Services\Communications\Routing\Rules;

use App\Enum\Communication\AgentAvailabilityStatus;
use App\Models\Dialler\AgentStatus;
use App\Services\Communications\Routing\RoutingContext;
use App\Services\Communications\Routing\RoutingDecision;
use App\Services\Communications\Routing\RoutingRule;

class RouteAnyAgentRule implements RoutingRule {

    public function handle(RoutingContext $context): ?RoutingDecision {
        $solicitorId = $context->solicitor->id;

        $statuses = AgentStatus::query()
            ->where('solicitor_id', $solicitorId)
            ->where('status', 'available')
            ->inRandomOrder()
            ->get();

        if ($statuses->isEmpty()) {
            return RoutingDecision::voicemail('not_available');
        }

        return RoutingDecision::dialAgents(
            agentIds: $statuses->pluck('agent_id')->all(),
            reason: 'any_available_agents',
        );
    }
}