<?php

namespace classes;

require_once WD . '/interfaces/shelly_transport_i.php';
require_once WD . '/classes/shelly.php';

use interfaces\shelly_transport_i;

class cloud_shelly_transport implements shelly_transport_i
{
    public function __construct(
        private readonly ?shelly $client = null,
        private readonly bool $logRelaySignals = true,
        private readonly ?edge_gateway_manager $manager = null
    )
    {
    }

    private function client(): shelly
    {
        return $this->client ?? new shelly();
    }

    public function requireModuleEnabled(): void
    {
        $this->client()->requireModuleEnabled();
    }

    public function requireValidSecretKey(): void
    {
        $this->client()->requireValidSecretKey();
    }

    public function sendPostRequest(string $endpoint, array $data, ?int $department_id = null): array|object|null
    {
        try {
            $response = $this->client()->sendPostRequest($endpoint, $data);
            $this->logRelaySignal($endpoint, $data, $department_id, $response, null);
            return $response;
        } catch (\Throwable $exception) {
            $this->logRelaySignal($endpoint, $data, $department_id, null, $exception);
            throw $exception;
        }
    }

    private function logRelaySignal(
        string $endpoint,
        array $data,
        ?int $department_id,
        array|object|null $response,
        ?\Throwable $exception
    ): void {
        if (!$this->logRelaySignals || $department_id === null || $department_id <= 0 || !$this->isRelayEndpoint($endpoint)) {
            return;
        }

        try {
            $this->manager()->appendRelayTransportLog(
                $department_id,
                $endpoint,
                $data,
                $response,
                'cloud',
                $exception?->getMessage()
            );
        } catch (\Throwable) {
        }
    }

    private function isRelayEndpoint(string $endpoint): bool
    {
        return in_array($endpoint, ['/v2/devices/api/get', '/v2/devices/api/set/switch'], true);
    }

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