<?php

namespace App\Services\Communications\Routing\Rules;

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

class RouteQueueFallbackRule implements RoutingRule {
    public function __construct(
        protected QueueSelectionService $queues,
    ) {
    }

    public function handle(RoutingContext $context): ?RoutingDecision {
        $queueType = $context->calledNumber->type?->default_queue_type;

        if (!$queueType) {
            return null;
        }

        $queue = $this->queues->findActiveByType(
            solicitorId: $context->solicitor->id,
            type: $queueType,
        );

        if (!$queue) {
            return null;
        }

        return RoutingDecision::enqueue(
            queueId: $queue->id,
            reason: 'fallback_to_default_queue_type',
            meta: [
                'queue_type' => $queueType,
            ],
        );
    }
}