<?php

namespace App\Services\Communications\Routing\Rules;

use App\Services\Communications\AgentPresenceService;
use App\Services\Communications\Routing\RoutingContext;
use App\Services\Communications\Routing\RoutingDecision;
use App\Services\Communications\Routing\RoutingRule;

class RouteAssignedAgentRule implements RoutingRule {
    public function __construct(
        protected AgentPresenceService $presence,
    ) {
    }

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

        if (!$communicable || !method_exists($communicable, 'getAssignedAgentId')) {
            return null;
        }

        $agentId = $communicable->getAssignedAgentId();

        if (!$agentId) {
            return null;
        }

        if (!$this->presence->isAvailable($context->solicitor->id, $agentId)) {
            return null;
        }

        return RoutingDecision::dialAgent(
            agentId: $agentId,
            reason: 'assigned_agent_available',
        );
    }
}