import * as plugins from '../../plugins.js';
import type { OpsServer } from '../classes.opsserver.js';
import * as interfaces from '../../../ts_interfaces/index.js';
import { requireAdminIdentity } from '../helpers/guards.js';
import { toApiData, toApiDataArray } from '../helpers/serialization.js';

export class SslHandler {
  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_ObtainCertificate>(
        'obtainCertificate',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          await this.opsServerRef.oneboxRef.ssl.obtainCertificate(dataArg.domain, false);
          const certificate = await this.opsServerRef.oneboxRef.ssl.getCertificate(dataArg.domain);
          return { certificate: toApiData(certificate) as unknown as interfaces.data.ICertificate };
        },
      ),
    );

    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_ListCertificates>(
        'listCertificates',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          const certificates = await this.opsServerRef.oneboxRef.ssl.listCertificates();
          return { certificates: toApiDataArray(certificates) as unknown as interfaces.data.ICertificate[] };
        },
      ),
    );

    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetCertificate>(
        'getCertificate',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          const certificate = await this.opsServerRef.oneboxRef.ssl.getCertificate(dataArg.domain);
          if (!certificate) {
            throw new plugins.typedrequest.TypedResponseError('Certificate not found');
          }
          return { certificate: toApiData(certificate) as unknown as interfaces.data.ICertificate };
        },
      ),
    );

    this.typedrouter.addTypedHandler(
      new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_RenewCertificate>(
        'renewCertificate',
        async (dataArg) => {
          await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
          await this.opsServerRef.oneboxRef.ssl.renewCertificate(dataArg.domain);
          const certificate = await this.opsServerRef.oneboxRef.ssl.getCertificate(dataArg.domain);
          return { certificate: toApiData(certificate) as unknown as interfaces.data.ICertificate };
        },
      ),
    );
  }
}
