import * as cdk from "aws-cdk-lib";
import { CfnEventDataStore, CfnTrail, Trail } from "aws-cdk-lib/aws-cloudtrail";
import { RetentionDays } from "aws-cdk-lib/aws-logs";
import { Bucket } from "aws-cdk-lib/aws-s3";
import { Construct } from "constructs";

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

export class CloudTrailStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props: StackProps) {
    super(scope, id, props);
    const { accountAlias } = props;

    const bucket = new Bucket(this, "Bucket", {
      bucketName: `${accountAlias}-cloudtrail`,
      versioned: true,
      enforceSSL: true,
    });

    // CloudTrail
    const trail = new Trail(this, "CloudTrail", {
      trailName: `${accountAlias}-cloudtrail`,
      sendToCloudWatchLogs: false,
      cloudWatchLogsRetention: RetentionDays.INFINITE,
      bucket,
    });
    const cfnTrail = trail.node.defaultChild as CfnTrail;
    cfnTrail.eventSelectors = [
      {
        dataResources: [
          {
            type: "AWS::S3::Object",
            values: ["arn:aws:s3"],
          },
          {
            type: "AWS::Lambda::Function",
            values: ["arn:aws:lambda"],
          },
        ],
        includeManagementEvents: false,
        readWriteType: "All",
      },
    ];

    // CloudTrail Lake
    new CfnEventDataStore(this, "EventDataStore", {
      advancedEventSelectors: [
        {
          fieldSelectors: [
            {
              field: "eventCategory",
              equalTo: ["Management"],
            },
          ],
        },
        {
          fieldSelectors: [
            {
              field: "eventCategory",
              equalTo: ["Data"],
            },
            {
              field: "resources.type",
              equalTo: ["AWS::Lambda::Function"],
            },
          ],
        },
        {
          fieldSelectors: [
            {
              field: "eventCategory",
              equalTo: ["Data"],
            },
            {
              field: "resources.type",
              equalTo: ["AWS::S3::Object"],
            },
          ],
        },
      ],
    });
  }
}
