<?php

namespace classes;

use Exception;

class edge_gateway_registry_service
{
    public function __construct(private readonly ?edge_gateway_manager $manager = null)
    {
        edge_gateway_schema_bootstrap::ensureTables();
    }

    public function createInstallToken(int $departmentId, ?string $label, ?int $createdBy = null): array
    {
        return $this->manager()->createInstallToken($departmentId, $label, $createdBy);
    }

    /**
     * @throws Exception
     */
    public function verifyInstallToken(string $plainToken): array
    {
        return $this->manager()->verifyInstallToken($plainToken);
    }

    /**
     * @throws Exception
     */
    public function getInstallTokenStatus(int $claimTokenId): array
    {
        return $this->manager()->getInstallTokenStatus($claimTokenId);
    }

    /**
     * @throws Exception
     */
    public function reportInstallTokenStatus(string $plainToken, array $payload): array
    {
        return $this->manager()->reportInstallTokenStatus($plainToken, $payload);
    }

    /**
     * @throws Exception
     */
    public function claimGateway(
        string $token,
        string $hostname,
        ?string $installedVersion = null,
        array $metadata = []
    ): array {
        $payload = $this->manager()->claimGateway($token, $hostname, $installedVersion, $metadata);
        unset($payload['broker_url']);

        return $payload;
    }

    /**
     * @throws Exception
     */
    public function recordHeartbeat(int $gatewayId, string $plainToken, array $payload): array
    {
        return $this->manager()->recordHeartbeat($gatewayId, $plainToken, $payload);
    }

    /**
     * @throws Exception
     */
    public function updateGatewayMetadata(int $gatewayId, array $payload, ?int $userId = null): array
    {
        return $this->manager()->updateGatewayMetadata($gatewayId, $payload, $userId);
    }

    /**
     * @return array<int,array<string,mixed>>
     * @throws Exception
     */
    public function setRelayBindings(int $gatewayId, array $bindings, ?int $userId = null): array
    {
        return $this->manager()->setRelayBindings($gatewayId, $bindings, $userId);
    }

    /**
     * @throws Exception
     */
    public function deleteGateway(int $gatewayId, ?int $userId = null): array
    {
        return $this->manager()->deleteGateway($gatewayId, $userId);
    }

    /**
     * @throws Exception
     */
    public function setDepartmentTransportMode(int $departmentId, string $transportMode, ?int $userId = null): array
    {
        return $this->manager()->setDepartmentTransportMode($departmentId, $transportMode, $userId);
    }

    public function getDepartmentTransportMode(int $departmentId): string
    {
        return $this->manager()->getDepartmentTransportMode($departmentId);
    }

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