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

import { OneboxReverseProxy } from '../ts/classes/reverseproxy.ts';
import type { IService } from '../ts/types.ts';

class FakeDatabase {
  public settings = new Map<string, string>();
  public services: IService[] = [];

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

  getAllServices(): IService[] {
    return this.services;
  }

  getServiceByID(id: number): IService | null {
    return this.services.find((service) => service.id === id) ?? null;
  }

  getAllSSLCertificates(): [] {
    return [];
  }
}

Deno.test('OneboxReverseProxy loads Admin UI domain as local SmartProxy route', async () => {
  const database = new FakeDatabase();
  database.settings.set('adminUiDomain', 'onebox.example.com');
  database.settings.set('serverIP', '203.0.113.10');

  const reverseProxy = new OneboxReverseProxy({ database } as any);
  const routes: Array<{ domain: string; upstream: string }> = [];
  (reverseProxy as any).smartProxy = {
    clear: () => routes.splice(0, routes.length),
    addRoute: async (domain: string, upstream: string) => {
      routes.push({ domain, upstream });
    },
    getCertificates: () => [],
  };

  await reverseProxy.reloadRoutes();

  assertEquals(routes, [
    {
      domain: 'onebox.example.com',
      upstream: '203.0.113.10:3000',
    },
  ]);
});
