import * as plugins from '../smartacme.plugins.js';
import type { IChallengeHandler } from './IChallengeHandler.js';

/**
 * DNS-01 challenge handler using CloudflareAccount and Smartdns.
 */
export class Dns01Handler implements IChallengeHandler<plugins.tsclass.network.IDnsChallenge> {
  private cf: plugins.tsclass.network.IConvenientDnsProvider;
  private smartdns: plugins.smartdnsClient.Smartdns;

  constructor(
    convenientDnsProvider: plugins.tsclass.network.IConvenientDnsProvider,
    smartdnsInstance?: plugins.smartdnsClient.Smartdns,
  ) {
    this.cf = convenientDnsProvider;
    this.smartdns = smartdnsInstance ?? new plugins.smartdnsClient.Smartdns({});
  }

  public getSupportedTypes(): string[] {
    return ['dns-01'];
  }

  public async prepare(ch: plugins.tsclass.network.IDnsChallenge): Promise<void> {
    // set DNS TXT record
    await this.cf.convenience.acmeSetDnsChallenge(ch);
  }

  public async cleanup(ch: plugins.tsclass.network.IDnsChallenge): Promise<void> {
    // remove DNS TXT record
    await this.cf.convenience.acmeRemoveDnsChallenge(ch);
  }

  public async checkWetherDomainIsSupported(domainArg: string): Promise<boolean> {
    return this.cf.convenience.isDomainSupported(domainArg);
  }
}