<?php

declare(strict_types=1);

usesApiSuite();

it('stores broker settings in edge gateway module config and uses them for shell sessions', function (): void {
    $department = api_fixtures()->createDepartment([
        'name' => 'Edge Gateway Config Department',
    ]);
    $session = api_fixtures()->createEdgeOperatorSession((int)$department['id']);
    $gateway = api_fixtures()->createClaimedEdgeGateway([
        'department_id' => (int)$department['id'],
        'label' => 'Config Gateway',
    ]);

    api_fixtures()->setModuleConfig('edgegateway', 'enabled', 'true', 'bool');
    api_fixtures()->setModuleConfig('edgegateway', 'default_release_channel', 'stable', 'string');
    api_fixtures()->setModuleConfig('edgegateway', 'default_update_window', '02:00-04:00', 'string');
    api_fixtures()->setModuleConfig('edgegateway', 'broker_url', 'http://edge-broker:4300', 'string');
    api_fixtures()->setModuleConfig('edgegateway', 'public_broker_url', '', 'string');
    api_fixtures()->setModuleConfig('edgegateway', 'broker_auth_mode', 'manager', 'string');
    api_fixtures()->setModuleConfig('edgegateway', 'broker_shared_secret', edge_test_broker_secret(), 'string');

    $update = api_client()->post('/edgegateway/config', [
        'enabled' => true,
        'default_release_channel' => 'canary',
        'default_update_window' => '01:00-02:00',
        'broker_url' => 'http://edge-broker.internal:4300',
        'public_broker_url' => 'https://broker.example.test/edge-broker',
        'broker_auth_mode' => 'manager',
    ], $session['headers']);

    $update
        ->assertStatus(200)
        ->assertEnvelope()
        ->assertSuccess();

    $config = api_client()->get('/edgegateway/config', $session['headers']);

    $config
        ->assertStatus(200)
        ->assertEnvelope()
        ->assertSuccess();

    $values = [];
    foreach ($config->data() as $entry) {
        $values[(string)$entry['variable']] = $entry['value'];
    }

    expect($values)
        ->toHaveKey('default_release_channel', 'canary')
        ->toHaveKey('broker_url', 'http://edge-broker.internal:4300')
        ->toHaveKey('public_broker_url', 'https://broker.example.test/edge-broker')
        ->toHaveKey('broker_auth_mode', 'manager')
        ->toHaveKey('broker_shared_secret', '');

    $presence = api_client()->post(
        '/edge-agent/internal/gateways/' . (int)$gateway['id'] . '/presence',
        [
            'status' => 'connected',
            'connection_id' => 'module-config-broker-presence',
        ],
        edge_test_broker_headers(['X-Edge-Broker-Secret' => edge_test_broker_secret()])
    );

    $presence
        ->assertStatus(200)
        ->assertEnvelope()
        ->assertSuccess();

    $shellSession = api_client()->post(
        '/edge-gateways/' . (int)$gateway['id'] . '/shell-sessions',
        ['reason' => 'Config broker URL validation'],
        $session['headers']
    );

    $shellSession
        ->assertStatus(201)
        ->assertEnvelope()
        ->assertSuccess();

    expect($shellSession->data())
        ->toHaveKey('broker_url', 'https://broker.example.test/edge-broker')
        ->toHaveKey('ws_url', 'wss://broker.example.test/edge-broker/ws/browser-shell')
        ->and($shellSession->data()['diagnostics']['public_broker_url_configured'] ?? null)
        ->toBeTrue()
        ->and($shellSession->data()['diagnostics']['broker_auth_mode'] ?? null)
        ->toBe('manager');
});

it('returns broker diagnostics for the current edge gateway module config values', function (): void {
    $department = api_fixtures()->createDepartment([
        'name' => 'Edge Gateway Diagnostics Department',
    ]);
    $session = api_fixtures()->createEdgeOperatorSession((int)$department['id']);

    api_fixtures()->setModuleConfig('edgegateway', 'enabled', 'true', 'bool');
    api_fixtures()->setModuleConfig('edgegateway', 'broker_url', 'http://127.0.0.1:1', 'string');
    api_fixtures()->setModuleConfig('edgegateway', 'public_broker_url', 'http://127.0.0.1:1/edge-broker', 'string');
    api_fixtures()->setModuleConfig('edgegateway', 'broker_auth_mode', 'manager', 'string');
    api_fixtures()->setModuleConfig('edgegateway', 'broker_shared_secret', 'diagnostic-secret', 'string');

    $response = api_client()->post('/edgegateway/config/broker-diagnostics', [
        'target' => 'all',
        'broker_url' => 'http://127.0.0.1:18080/metadata',
        'public_broker_url' => 'http://127.0.0.1:18081/metadata',
        'broker_auth_mode' => 'manager',
        'broker_shared_secret' => 'diagnostic-secret',
    ], $session['headers']);

    $response
        ->assertStatus(200)
        ->assertEnvelope()
        ->assertSuccess();

    expect($response->data())
        ->toHaveKey('internal_broker_connection')
        ->toHaveKey('public_broker_url')
        ->toHaveKey('broker_shared_secret')
        ->toHaveKey('broker_auth_mode', 'manager')
        ->toHaveKey('broker_shared_secret_configured', true)
        ->and($response->data()['internal_broker_connection']['url'] ?? null)
        ->toBe('http://127.0.0.1:1')
        ->and($response->data()['public_broker_url']['url'] ?? null)
        ->toBe('http://127.0.0.1:1/edge-broker')
        ->and($response->data()['internal_broker_connection']['ok'] ?? null)
        ->toBeFalse()
        ->and($response->data()['public_broker_url']['ok'] ?? null)
        ->toBeFalse()
        ->and($response->data()['broker_shared_secret']['ok'] ?? null)
        ->toBeFalse();
});
