import * as cdk from "aws-cdk-lib";
import { BlockPublicAccess, Bucket, BucketEncryption } from "aws-cdk-lib/aws-s3";
import { StringParameter } from "aws-cdk-lib/aws-ssm";
import { Construct } from "constructs";

interface StackProps extends cdk.StackProps {
  readonly stage: string;
}

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

    const { stage } = props;

    const usageEventRequestsBucket = new Bucket(this, "UsageEventRequestsBucket", {
      bucketName: `${stage}-ai-unit-usage-event-requests`,
      blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
      encryption: BucketEncryption.S3_MANAGED,
      enforceSSL: true,
      removalPolicy: cdk.RemovalPolicy.DESTROY,
      autoDeleteObjects: true,
      versioned: true,
      lifecycleRules: [
        {
          id: "DeleteUsageEventRequests",
          expiration: cdk.Duration.days(365), //オブジェクトの現行バージョンを有効期限切れにする
          noncurrentVersionExpiration: cdk.Duration.days(1), //オブジェクトの非現行バージョンを完全に削除
          abortIncompleteMultipartUploadAfter: cdk.Duration.days(1), //有効期限切れのオブジェクト削除マーカーまたは不完全なマルチパートアップロードを削除
        },
      ],
    });

    new StringParameter(this, "UsageEventRequestsBucketNameParameter", {
      parameterName: `/${stage}/usage-event-requests-bucket-name`,
      stringValue: usageEventRequestsBucket.bucketName,
    });
  }
}
