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 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 = this.opsServerRef.oneboxRef.ssl.getCertificate(dataArg.domain);
          return { certificate: 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 = this.opsServerRef.oneboxRef.ssl.listCertificates();
          return { certificates: 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 = this.opsServerRef.oneboxRef.ssl.getCertificate(dataArg.domain);
          if (!certificate) {
            throw new plugins.typedrequest.TypedResponseError('Certificate not found');
          }
          return { certificate: 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 = this.opsServerRef.oneboxRef.ssl.getCertificate(dataArg.domain);
          return { certificate: certificate as unknown as interfaces.data.ICertificate };
        },
      ),
    );
  }
}
