import * as cdk from "aws-cdk-lib";
import * as acm from "aws-cdk-lib/aws-certificatemanager";
import * as route53 from "aws-cdk-lib/aws-route53";
import { Construct } from "constructs";
import {
  CONTRACT_USER_POOL_CUSTOM_DOMAIN_PREFIX,
  MANAGEMENT_CONSOLE_WILDCARD_DOMAIN_PREFIX,
  MANAGEMENT_M2M_POOL_CUSTOM_DOMAIN_PREFIX,
  MANAGEMENT_USER_POOL_CUSTOM_DOMAIN_PREFIX,
} from "./const";

interface StackProps extends cdk.StackProps {
  stage: string;
  hostedZone: route53.IHostedZone;
  enableUserPoolCustomDomain: boolean;
}

export class AcmUsEast1Stack extends cdk.Stack {
  public readonly userPoolCertificate: acm.ICertificate;
  public readonly managementUserCertificate: acm.ICertificate;
  public readonly contractUserPoolCertificate: acm.ICertificate;
  public readonly managementConsoleCertificate: acm.ICertificate;

  constructor(scope: Construct, id: string, props: StackProps) {
    super(scope, id, props);
    const { hostedZone, enableUserPoolCustomDomain } = props;

    if (enableUserPoolCustomDomain) {
      const managementM2MPoolDomain = `${MANAGEMENT_M2M_POOL_CUSTOM_DOMAIN_PREFIX}.${hostedZone.zoneName}`;
      this.userPoolCertificate = new acm.Certificate(this, "UserPoolCertificate", {
        domainName: managementM2MPoolDomain,
        validation: acm.CertificateValidation.fromDns(hostedZone),
      });

      const managementUserPoolDomain = `${MANAGEMENT_USER_POOL_CUSTOM_DOMAIN_PREFIX}.${hostedZone.zoneName}`;
      this.managementUserCertificate = new acm.Certificate(this, "ManagementUserPoolCertificate", {
        domainName: managementUserPoolDomain,
        validation: acm.CertificateValidation.fromDns(hostedZone),
      });

      const contractDomain = `${CONTRACT_USER_POOL_CUSTOM_DOMAIN_PREFIX}.${hostedZone.zoneName}`;
      this.contractUserPoolCertificate = new acm.Certificate(this, "ContractUserPoolCertificate", {
        domainName: contractDomain,
        validation: acm.CertificateValidation.fromDnsMultiZone({
          [contractDomain]: hostedZone,
        }),
      });
    }

    const consoleDomain = `${MANAGEMENT_CONSOLE_WILDCARD_DOMAIN_PREFIX}.${hostedZone.zoneName}`;
    this.managementConsoleCertificate = new acm.Certificate(this, "ManagementConsoleCertificate", {
      domainName: consoleDomain,
      validation: acm.CertificateValidation.fromDns(hostedZone),
    });
  }
}
