<?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 {
        $statuses = AgentStatus::query()
            ->where('solicitor_id', $context->solicitor->id)
            ->where('status', 'available')
//            ->where('status_changed_at', '>=', now()->subMinutes(5))
            ->whereHas('agent')
            ->inRandomOrder()
            ->get();

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

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