import { assert, assertEquals } from '@std/assert';

import { ManagedDcRouterManager } from '../ts/classes/managed-dcrouter.ts';

class FakeDatabase {
  public settings = new Map<string, string>();
  public secretSettings = new Map<string, string>();

  getSetting(key: string): string | null {
    return this.settings.get(key) ?? null;
  }

  setSetting(key: string, value: string): void {
    this.settings.set(key, value);
  }

  async getSecretSetting(key: string): Promise<string | null> {
    return this.secretSettings.get(key) ?? null;
  }

  async setSecretSetting(key: string, value: string): Promise<void> {
    this.secretSettings.set(key, value);
  }
}

Deno.test('ManagedDcRouterManager persists default managed gateway settings', async () => {
  const database = new FakeDatabase();
  const manager = new ManagedDcRouterManager({ database } as any);

  assertEquals(manager.getMode(), 'managed');

  await manager.prepareGatewaySettings();

  assertEquals(database.getSetting('dcrouterMode'), 'managed');
  assertEquals(manager.getMode(), 'managed');
  assertEquals(database.getSetting('dcrouterGatewayUrl'), 'http://127.0.0.1:3300');
  assertEquals(database.getSetting('dcrouterTargetHost'), 'onebox-smartproxy');
  assertEquals(database.getSetting('dcrouterTargetPort'), '80');
  assert(database.getSetting('dcrouterGatewayClientId')?.startsWith('onebox-'));
  assert((await database.getSecretSetting('dcrouterManagedAdminApiToken'))?.startsWith('dcr_'));
});

Deno.test('ManagedDcRouterManager keeps existing external gateway default external', async () => {
  const database = new FakeDatabase();
  database.setSetting('dcrouterGatewayUrl', 'https://edge.example.com');
  const manager = new ManagedDcRouterManager({ database } as any);

  assertEquals(manager.getMode(), 'external');

  await manager.prepareGatewaySettings();

  assertEquals(database.getSetting('dcrouterMode'), null);
  assertEquals(database.getSetting('dcrouterTargetHost'), null);
});
