import * as plugins from '../../plugins.ts';
import type { OpsServer } from '../classes.opsserver.ts';
import * as interfaces from '../../../ts_interfaces/index.ts';
import { requireAdminIdentity } from '../helpers/guards.ts';

export class DnsHandler {
  public typedrouter = new plugins.typedrequest.TypedRouter();

  constructor(private opsServerRef: OpsServer) {
    this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
    this.registerHandlers();
  }

  private registerHandlers(): void {
    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetDnsRecords>(
        'getDnsRecords',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          const records = this.opsServerRef.oneboxRef.dns.listDNSRecords();
          return { records };
        },
      ),
    );

    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_CreateDnsRecord>(
        'createDnsRecord',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          await this.opsServerRef.oneboxRef.dns.addDNSRecord(dataArg.domain, dataArg.value);
          const records = this.opsServerRef.oneboxRef.dns.listDNSRecords();
          const record = records.find((r: any) => r.domain === dataArg.domain);
          return { record: record! };
        },
      ),
    );

    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_DeleteDnsRecord>(
        'deleteDnsRecord',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          await this.opsServerRef.oneboxRef.dns.removeDNSRecord(dataArg.domain);
          return { ok: true };
        },
      ),
    );

    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_SyncDns>(
        'syncDns',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          if (!this.opsServerRef.oneboxRef.dns.isConfigured()) {
            throw new plugins.typedrequest.TypedResponseError('DNS manager not configured');
          }
          await this.opsServerRef.oneboxRef.dns.syncFromCloudflare();
          const records = this.opsServerRef.oneboxRef.dns.listDNSRecords();
          return { records };
        },
      ),
    );

    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetGatewayDnsRecords>(
        'getGatewayDnsRecords',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          const records = await this.opsServerRef.oneboxRef.externalGateway.getGatewayDnsRecords();
          return { records };
        },
      ),
    );
  }
}
