<?php

namespace classes;

require_once WD . '/interfaces/universal_module_i.php';
require_once WD . '/modules/edgegateway/edgegateway_c.php';

use Exception;
use interfaces\universal_module_i;
use modules\edgegateway\edgegateway_c;

class edgegateway implements universal_module_i
{
    public edgegateway_c $config;

    public function __construct()
    {
        $this->config = new edgegateway_c();
    }

    /**
     * @throws Exception
     */
    public function requireModuleEnabled(): void
    {
        if (!$this->config->enabled->isTrue()) {
            throw new Exception('The edge gateway module is not enabled');
        }
    }

    public function isEnabled(): bool
    {
        try {
            return $this->config->enabled->isTrue();
        } catch (Exception $exception) {
            return false;
        }
    }

    public function defaultReleaseChannel(): string
    {
        $configured = trim((string)$this->config->default_release_channel->getVariableValue());
        return $configured !== '' ? $configured : 'stable';
    }

    public function defaultUpdateWindow(): string
    {
        $configured = trim((string)$this->config->default_update_window->getVariableValue());
        return $configured !== '' ? $configured : '02:00-04:00';
    }

    public function brokerUrl(): string
    {
        $configured = trim((string)$this->config->broker_url->getVariableValue());
        if ($configured !== '') {
            return rtrim($configured, '/');
        }

        $fallback = trim((string)(getenv('EDGE_BROKER_URL') ?: ''));
        return $fallback !== '' ? rtrim($fallback, '/') : '';
    }

    public function publicBrokerUrl(): string
    {
        $configured = trim((string)$this->config->public_broker_url->getVariableValue());
        if ($configured !== '') {
            return rtrim($configured, '/');
        }

        $fallback = trim((string)(getenv('EDGE_PUBLIC_BROKER_URL') ?: ''));
        return $fallback !== '' ? rtrim($fallback, '/') : '';
    }

    public function brokerAuthMode(): string
    {
        $configured = trim((string)$this->config->broker_auth_mode->getVariableValue());
        return $configured !== '' ? $configured : 'manager';
    }

    public function brokerSharedSecret(): string
    {
        $configured = trim((string)$this->config->broker_shared_secret->getVariableValue());
        if ($configured !== '') {
            return $configured;
        }

        return trim((string)(getenv('EDGE_BROKER_SHARED_SECRET') ?: ''));
    }
}
