<?php

namespace classes;

require_once WD . '/interfaces/shelly_transport_i.php';
require_once WD . '/classes/cloud_shelly_transport.php';
require_once WD . '/classes/gateway_shelly_transport.php';

use interfaces\shelly_transport_i;

class shelly_transport_resolver
{
    public function __construct(
        private readonly ?edge_gateway_manager $edgeGatewayManager = null,
        private readonly ?shelly_transport_i $cloudTransport = null,
        private readonly ?shelly_transport_i $gatewayTransport = null
    ) {
    }

    public function resolveForDepartment(int $departmentId, ?string $transportOverride = null): shelly_transport_i
    {
        $override = strtolower(trim((string)$transportOverride));
        $explicitLocalOverride = in_array($override, ['local', edge_gateway_manager::TRANSPORT_MODE_GATEWAY], true);
        if ($override === 'local') {
            $override = edge_gateway_manager::TRANSPORT_MODE_GATEWAY;
        }

        if ($override === edge_gateway_manager::TRANSPORT_MODE_GATEWAY) {
            return $this->gatewayTransport ?? new gateway_shelly_transport($this->manager(), $explicitLocalOverride);
        }

        if ($override === edge_gateway_manager::TRANSPORT_MODE_CLOUD) {
            return $this->cloudTransport ?? new cloud_shelly_transport();
        }

        $mode = $this->manager()->getDepartmentTransportMode($departmentId);
        if ($mode === edge_gateway_manager::TRANSPORT_MODE_GATEWAY) {
            return $this->gatewayTransport ?? new gateway_shelly_transport($this->manager());
        }

        return $this->cloudTransport ?? new cloud_shelly_transport();
    }

    private function manager(): edge_gateway_manager
    {
        return $this->edgeGatewayManager ?? new edge_gateway_manager();
    }
}
