import * as cdk from "aws-cdk-lib";
import * as logs from "aws-cdk-lib/aws-logs";
import { Construct } from "constructs";

interface StackProps extends cdk.StackProps {
  stage: string;
  enableFrontendAccessLog: boolean;
  managementConsoleDistributionArn: string;
  managementConsoleLogBucketArn?: string;
}

export class LogDeliveryUsEast1Stack extends cdk.Stack {
  constructor(scope: Construct, id: string, props: StackProps) {
    super(scope, id, props);

    const { stage, enableFrontendAccessLog, managementConsoleDistributionArn, managementConsoleLogBucketArn } = props;

    if (enableFrontendAccessLog) {
      // Management Console Access Log
      const deliveryDestination = new logs.CfnDeliveryDestination(this, "ManagementConsoleLogDeliveryDestination", {
        name: `${stage}-management-console-cf-log-delivery-destination`,
        destinationResourceArn: managementConsoleLogBucketArn,
        outputFormat: "json",
      });
      const deliverySource = new logs.CfnDeliverySource(this, "ManagementConsoleLogDeliverySource", {
        name: `${stage}-management-console-cf-log-delivery-source`,
        logType: "ACCESS_LOGS",
        resourceArn: managementConsoleDistributionArn,
      });
      const delivery = new logs.CfnDelivery(this, "ManagementConsoleLogDelivery", {
        deliverySourceName: deliverySource.name,
        deliveryDestinationArn: deliveryDestination.attrArn,
        s3SuffixPath: "{yyyy}/{MM}/{dd}/",
      });
      delivery.addDependency(deliveryDestination);
      delivery.addDependency(deliverySource);
    }
  }
}
