import * as apigateway from "aws-cdk-lib/aws-apigateway";
import * as acm from "aws-cdk-lib/aws-certificatemanager";
import * as route53 from "aws-cdk-lib/aws-route53";
import * as route53targets from "aws-cdk-lib/aws-route53-targets";
import * as ssm from "aws-cdk-lib/aws-ssm";
import { Construct } from "constructs";
interface ApiDomainProps {
  stage: string;
  domainName: string;
  hostedZone: route53.IHostedZone;
  restApi: apigateway.IRestApi;
}

export class ApiDomain extends Construct {
  constructor(scope: Construct, id: string, props: ApiDomainProps) {
    super(scope, id);
    const { stage, domainName, hostedZone, restApi } = props;

    const apiDomain = new apigateway.DomainName(this, "ApiDomainName", {
      domainName: domainName,
      certificate: new acm.Certificate(this, "Certificate", {
        domainName: domainName,
        validation: acm.CertificateValidation.fromDns(hostedZone),
      }),
      securityPolicy: apigateway.SecurityPolicy.TLS_1_2,
      endpointType: apigateway.EndpointType.REGIONAL,
    });
    new apigateway.BasePathMapping(this, "BasePathMapping", {
      domainName: apiDomain,
      restApi,
    });
    const record = new route53.ARecord(this, "Record", {
      zone: hostedZone,
      recordName: domainName,
      target: route53.RecordTarget.fromAlias(new route53targets.ApiGatewayDomain(apiDomain)),
    });
    new ssm.StringParameter(this, "ApiDomainNameParameter", {
      parameterName: ApiDomain.parameterName(stage, restApi.restApiName),
      stringValue: record.domainName,
    });
  }

  public static parameterName(stage: string, apiName: string): string {
    return `/${stage}/${apiName}-domain-name`;
  }
}
