import * as cdk from "aws-cdk-lib";
import * as codebuild from "aws-cdk-lib/aws-codebuild";
import { IVpc } from "aws-cdk-lib/aws-ec2";
import * as events from "aws-cdk-lib/aws-events";
import * as iam from "aws-cdk-lib/aws-iam";
import { LogGroup, RetentionDays } from "aws-cdk-lib/aws-logs";
import { CfnSchedule } from "aws-cdk-lib/aws-scheduler";
import * as ssm from "aws-cdk-lib/aws-ssm";
import { Trigger } from "aws-cdk-lib/triggers";
import { Construct } from "constructs";
import { GITHUB_OWNER, GITHUB_REPO } from "./const";

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

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

    const { stage, commitSha, vpc } = props;

    // secret names are dynamically resolved in the build environment
    const dbClusterSecretName = ssm.StringParameter.fromStringParameterAttributes(this, "DbClusterAdminSecretName", {
      parameterName: `/${stage}/db-admin-secret-name`,
      forceDynamicReference: true,
    }).stringValue;
    const dbClusterAppSecretName = ssm.StringParameter.fromStringParameterAttributes(this, "DbClusterAppSecretName", {
      parameterName: `/${stage}/db-app-secret-name`,
      forceDynamicReference: true,
    }).stringValue;
    const dbClusterClientDeveloperSecretName = ssm.StringParameter.fromStringParameterAttributes(
      this,
      "DbClusterClientDeveloperSecretName",
      {
        parameterName: `/${stage}/db-client-developer-secret-name`,
        forceDynamicReference: true,
      },
    ).stringValue;
    const dbClusterWatcherSecretName = ssm.StringParameter.fromStringParameterAttributes(
      this,
      "DbClusterWatcherSecretName",
      {
        parameterName: `/${stage}/db-watcher-secret-name`,
        forceDynamicReference: true,
      },
    ).stringValue;

    const gitHubSource = codebuild.Source.gitHub({
      owner: GITHUB_OWNER,
      repo: GITHUB_REPO,
      branchOrRef: commitSha,
    });

    const toolRole = new iam.Role(this, "ToolRole", {
      assumedBy: new iam.ServicePrincipal("codebuild.amazonaws.com"),
      managedPolicies: [iam.ManagedPolicy.fromAwsManagedPolicyName("AdministratorAccess")],
    });

    const migrationPostgresRunnerBuildSpecObject = {
      version: 0.2,
      env: {
        shell: "/bin/bash",
        "secrets-manager": {
          POSTGRES_HOST: `${dbClusterSecretName}:host`,
          POSTGRES_PORT: `${dbClusterSecretName}:port`,
          POSTGRES_USER: `${dbClusterSecretName}:username`,
          POSTGRES_PASSWORD: `${dbClusterSecretName}:password`,
          POSTGRES_DB: `${dbClusterSecretName}:dbname`,
          POSTGRES_APP_USER: `${dbClusterAppSecretName}:username`,
          POSTGRES_APP_PASSWORD: `${dbClusterAppSecretName}:password`,
          POSTGRES_CLIENT_DEVELOPER_USER: `${dbClusterClientDeveloperSecretName}:username`,
          POSTGRES_CLIENT_DEVELOPER_PASSWORD: `${dbClusterClientDeveloperSecretName}:password`,
          POSTGRES_WATCHER_USER: `${dbClusterWatcherSecretName}:username`,
          POSTGRES_WATCHER_PASSWORD: `${dbClusterWatcherSecretName}:password`,
        },
      },
      phases: {
        build: {
          commands: [
            "cd ${CODEBUILD_SRC_DIR}/database/migration",
            "pip install -r requirements.txt",
            "alembic ${MODE} ${REVISION}",
          ],
        },
      },
    };

    const migrationPostgresRunnerProject = new codebuild.Project(this, "MigrationPostgresRunnerProject", {
      projectName: `${stage}-migration-postgres-runner`,
      role: toolRole,
      buildSpec: codebuild.BuildSpec.fromObject(migrationPostgresRunnerBuildSpecObject),
      environment: {
        privileged: true,
        buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
        environmentVariables: {
          MODE: {
            type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
            value: "upgrade",
          },
          REVISION: {
            type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
            value: "head",
          },
        },
      },
      vpc,
      source: gitHubSource,
      cache: codebuild.Cache.local(codebuild.LocalCacheMode.DOCKER_LAYER, codebuild.LocalCacheMode.CUSTOM),
      logging: {
        cloudWatch: {
          logGroup: new LogGroup(this, "MigrationPostgresRunnerLogGroup", {
            retention: RetentionDays.ONE_YEAR + RetentionDays.SIX_MONTHS,
            removalPolicy: cdk.RemovalPolicy.DESTROY,
          }),
        },
      },
    });

    const migrationPostgresTrigger = new Trigger(this, "MigrationTrigger", {
      handler: new cdk.aws_lambda.Function(this, "MigrationTriggerHandler", {
        runtime: cdk.aws_lambda.Runtime.NODEJS_22_X,
        description: `Trigger CodeBuild to run DB migration. Commit: ${commitSha}`, // headが更新されたデプロイの度に実行
        timeout: cdk.Duration.minutes(15),
        code: cdk.aws_lambda.Code.fromAsset("lambda/codebuild-kicker"),
        handler: "index.handler",
        environment: {
          PROJECT_NAME: migrationPostgresRunnerProject.projectName,
        },
        initialPolicy: [
          new iam.PolicyStatement({
            actions: ["codebuild:StartBuild", "codebuild:BatchGetBuilds"],
            resources: [migrationPostgresRunnerProject.projectArn],
          }),
        ],
      }),
      executeOnHandlerChange: true,
      executeAfter: [migrationPostgresRunnerProject],
      timeout: cdk.Duration.minutes(15),
    });
    migrationPostgresTrigger.node.addDependency(migrationPostgresRunnerProject);

    const pricesCollectorBuildSpecObject = {
      version: 0.2,
      env: {
        shell: "/bin/bash",
        "secrets-manager": {
          POSTGRES_HOST: `${dbClusterSecretName}:host`,
          POSTGRES_PORT: `${dbClusterSecretName}:port`,
          POSTGRES_USER: `${dbClusterSecretName}:username`,
          POSTGRES_PASSWORD: `${dbClusterSecretName}:password`,
          POSTGRES_DB: `${dbClusterSecretName}:dbname`,
        },
      },
      phases: {
        build: {
          commands: [
            "cd ${CODEBUILD_SRC_DIR}/infra/stage/scripts",
            "pip install -r requirements.txt",
            "python prices_collector.py",
          ],
        },
      },
    };

    const pricesCollectorProject = new codebuild.Project(this, "PricesCollectorProject", {
      projectName: `${stage}-prices-collector`,
      role: toolRole,
      buildSpec: codebuild.BuildSpec.fromObject(pricesCollectorBuildSpecObject),
      environment: {
        privileged: true,
        buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
      },
      vpc,
      source: gitHubSource,
      cache: codebuild.Cache.local(codebuild.LocalCacheMode.DOCKER_LAYER, codebuild.LocalCacheMode.CUSTOM),
      logging: {
        cloudWatch: {
          logGroup: new LogGroup(this, "PricesCollectorLogGroup", {
            retention: RetentionDays.ONE_YEAR + RetentionDays.SIX_MONTHS,
            removalPolicy: cdk.RemovalPolicy.DESTROY,
          }),
        },
      },
    });

    const pricesCollectorTrigger = new Trigger(this, "PricesCollectorTrigger", {
      handler: new cdk.aws_lambda.Function(this, "PricesCollectorTriggerHandler", {
        runtime: cdk.aws_lambda.Runtime.NODEJS_22_X,
        description: `Trigger CodeBuild to run prices_collector. Commit: ${commitSha}`, // headが更新されたデプロイの度に実行
        timeout: cdk.Duration.minutes(15),
        code: cdk.aws_lambda.Code.fromAsset("lambda/codebuild-kicker"),
        handler: "index.handler",
        environment: {
          PROJECT_NAME: pricesCollectorProject.projectName,
        },
        initialPolicy: [
          new iam.PolicyStatement({
            actions: ["codebuild:StartBuild", "codebuild:BatchGetBuilds"],
            resources: [pricesCollectorProject.projectArn],
          }),
        ],
      }),
      executeOnHandlerChange: true,
      executeAfter: [pricesCollectorProject],
      timeout: cdk.Duration.minutes(15),
    });
    pricesCollectorTrigger.node.addDependency(pricesCollectorProject);

    const fixturePostgresRunnerBuildSpecObject = {
      version: 0.2,
      env: {
        shell: "/bin/bash",
        "secrets-manager": {
          POSTGRES_HOST: `${dbClusterSecretName}:host`,
          POSTGRES_PORT: `${dbClusterSecretName}:port`,
          POSTGRES_USER: `${dbClusterSecretName}:username`,
          POSTGRES_PASSWORD: `${dbClusterSecretName}:password`,
          POSTGRES_DB: `${dbClusterSecretName}:dbname`,
        },
      },
      phases: {
        build: {
          commands: [
            "cd ${CODEBUILD_SRC_DIR}/database/fixture",
            "pip install -r requirements.txt",
            "python fixture.py --csv-dir ${NAME}",
          ],
        },
      },
    };

    new codebuild.Project(this, "FixturePostgresRunnerProject", {
      projectName: `${stage}-fixture-postgres-runner`,
      role: toolRole,
      buildSpec: codebuild.BuildSpec.fromObject(fixturePostgresRunnerBuildSpecObject),
      environment: {
        privileged: true,
        buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
        environmentVariables: {
          NAME: {
            type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
            value: "integrationtest",
          },
        },
      },
      vpc,
      source: gitHubSource,
      cache: codebuild.Cache.local(codebuild.LocalCacheMode.DOCKER_LAYER, codebuild.LocalCacheMode.CUSTOM),
      logging: {
        cloudWatch: {
          logGroup: new LogGroup(this, "FixturePostgresRunnerLogGroup", {
            retention: RetentionDays.ONE_YEAR + RetentionDays.SIX_MONTHS,
            removalPolicy: cdk.RemovalPolicy.DESTROY,
          }),
        },
      },
    });
    const tenantCreatorBuildSpecObject = {
      version: 0.2,
      env: {
        shell: "/bin/bash",
        "parameter-store": {
          USER_POOL_ID: `/${stage}/user-pool-id`,
        },
        "secrets-manager": {
          POSTGRES_HOST: `${dbClusterSecretName}:host`,
          POSTGRES_PORT: `${dbClusterSecretName}:port`,
          POSTGRES_USER: `${dbClusterSecretName}:username`,
          POSTGRES_PASSWORD: `${dbClusterSecretName}:password`,
          POSTGRES_DB: `${dbClusterSecretName}:dbname`,
        },
      },
      phases: {
        build: {
          commands: [
            "cd ${CODEBUILD_SRC_DIR}/backend",
            "pip install -r requirements.txt",
            'python -m src.tools.tenant_creator --legal-name "$LEGAL_NAME" ${NAME:+--name "$NAME"} --whi-customer-ids "$WHI_CUSTOMER_IDS" --cydas-customer-ids "$CYDAS_CUSTOMER_IDS"',
          ],
        },
      },
    };

    new codebuild.Project(this, "TenantCreatorProject", {
      projectName: `${stage}-tenant-creator`,
      role: toolRole,
      buildSpec: codebuild.BuildSpec.fromObject(tenantCreatorBuildSpecObject),
      environment: {
        privileged: true,
        buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
      },
      environmentVariables: {
        LEGAL_NAME: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
        NAME: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
        WHI_CUSTOMER_IDS: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
        CYDAS_CUSTOMER_IDS: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
      },
      vpc,
      source: gitHubSource,
      cache: codebuild.Cache.local(codebuild.LocalCacheMode.DOCKER_LAYER, codebuild.LocalCacheMode.CUSTOM),
      logging: {
        cloudWatch: {
          logGroup: new LogGroup(this, "TenantCreatorLogGroup", {
            retention: RetentionDays.ONE_YEAR + RetentionDays.SIX_MONTHS,
            removalPolicy: cdk.RemovalPolicy.DESTROY,
          }),
        },
      },
    });

    const clientTenantCreatorBuildSpecObject = {
      version: 0.2,
      env: {
        shell: "/bin/bash",
        "secrets-manager": {
          POSTGRES_HOST: `${dbClusterSecretName}:host`,
          POSTGRES_PORT: `${dbClusterSecretName}:port`,
          POSTGRES_USER: `${dbClusterSecretName}:username`,
          POSTGRES_PASSWORD: `${dbClusterSecretName}:password`,
          POSTGRES_DB: `${dbClusterSecretName}:dbname`,
        },
      },
      phases: {
        build: {
          commands: [
            "cd ${CODEBUILD_SRC_DIR}/infra/stage/scripts",
            "pip install -r requirements.txt",
            "python client_tenant_creator.py --tenant-id $TENANT_ID --name $NAME",
          ],
        },
      },
    };

    new codebuild.Project(this, "ClientTenantCreatorProject", {
      projectName: `${stage}-client-tenant-creator`,
      role: toolRole,
      buildSpec: codebuild.BuildSpec.fromObject(clientTenantCreatorBuildSpecObject),
      environment: {
        privileged: true,
        buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
      },
      environmentVariables: {
        TENANT_ID: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
        NAME: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
      },
      vpc,
      source: gitHubSource,
      cache: codebuild.Cache.local(codebuild.LocalCacheMode.DOCKER_LAYER, codebuild.LocalCacheMode.CUSTOM),
      logging: {
        cloudWatch: {
          logGroup: new LogGroup(this, "ClientTenantCreatorLogGroup", {
            retention: RetentionDays.ONE_YEAR + RetentionDays.SIX_MONTHS,
            removalPolicy: cdk.RemovalPolicy.DESTROY,
          }),
        },
      },
    });

    const clientCreatorBuildSpecObject = {
      version: 0.2,
      env: {
        shell: "/bin/bash",
        "secrets-manager": {
          POSTGRES_HOST: `${dbClusterSecretName}:host`,
          POSTGRES_PORT: `${dbClusterSecretName}:port`,
          POSTGRES_USER: `${dbClusterSecretName}:username`,
          POSTGRES_PASSWORD: `${dbClusterSecretName}:password`,
          POSTGRES_DB: `${dbClusterSecretName}:dbname`,
        },
      },
      phases: {
        build: {
          commands: [
            "cd ${CODEBUILD_SRC_DIR}/infra/stage/scripts",
            "pip install -r requirements.txt",
            "python client_creator.py --stage $STAGE --client-name $CLIENT_NAME --client-stage $CLIENT_STAGE",
          ],
        },
      },
    };

    new codebuild.Project(this, "ClientCreatorProject", {
      projectName: `${stage}-client-creator`,
      role: toolRole,
      buildSpec: codebuild.BuildSpec.fromObject(clientCreatorBuildSpecObject),
      environment: {
        privileged: true,
        buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
      },
      environmentVariables: {
        STAGE: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: stage,
        },
        CLIENT_NAME: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
        CLIENT_STAGE: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
      },
      vpc,
      source: gitHubSource,
      cache: codebuild.Cache.local(codebuild.LocalCacheMode.DOCKER_LAYER, codebuild.LocalCacheMode.CUSTOM),
      logging: {
        cloudWatch: {
          logGroup: new LogGroup(this, "ClientCreatorLogGroup", {
            retention: RetentionDays.ONE_YEAR + RetentionDays.SIX_MONTHS,
            removalPolicy: cdk.RemovalPolicy.DESTROY,
          }),
        },
      },
    });

    const clientApiKeyCreatorBuildSpecObject = {
      version: 0.2,
      env: {
        shell: "/bin/bash",
        "secrets-manager": {
          POSTGRES_HOST: `${dbClusterSecretName}:host`,
          POSTGRES_PORT: `${dbClusterSecretName}:port`,
          POSTGRES_USER: `${dbClusterSecretName}:username`,
          POSTGRES_PASSWORD: `${dbClusterSecretName}:password`,
          POSTGRES_DB: `${dbClusterSecretName}:dbname`,
        },
      },
      phases: {
        build: {
          commands: [
            "cd ${CODEBUILD_SRC_DIR}/infra/stage/scripts",
            "pip install -r requirements.txt",
            "python client_api_key_creator.py --stage $STAGE --client-id $CLIENT_ID --client-name $CLIENT_NAME --client-stage $CLIENT_STAGE",
          ],
        },
      },
    };

    new codebuild.Project(this, "ClientApiKeyCreatorProject", {
      projectName: `${stage}-client-api-key-creator`,
      role: toolRole,
      buildSpec: codebuild.BuildSpec.fromObject(clientApiKeyCreatorBuildSpecObject),
      environment: {
        privileged: true,
        buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
      },
      environmentVariables: {
        STAGE: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: stage,
        },
        CLIENT_ID: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
        CLIENT_NAME: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
        CLIENT_STAGE: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
      },
      vpc,
      source: gitHubSource,
      cache: codebuild.Cache.local(codebuild.LocalCacheMode.DOCKER_LAYER, codebuild.LocalCacheMode.CUSTOM),
      logging: {
        cloudWatch: {
          logGroup: new LogGroup(this, "ClientApiKeyCreatorLogGroup", {
            retention: RetentionDays.ONE_YEAR + RetentionDays.SIX_MONTHS,
            removalPolicy: cdk.RemovalPolicy.DESTROY,
          }),
        },
      },
    });

    const quotaAllocationStatusUpdaterBuildSpecObject = {
      version: 0.2,
      env: {
        shell: "/bin/bash",
        "secrets-manager": {
          POSTGRES_HOST: `${dbClusterSecretName}:host`,
          POSTGRES_PORT: `${dbClusterSecretName}:port`,
          POSTGRES_USER: `${dbClusterSecretName}:username`,
          POSTGRES_PASSWORD: `${dbClusterSecretName}:password`,
          POSTGRES_DB: `${dbClusterSecretName}:dbname`,
        },
      },
      phases: {
        build: {
          commands: [
            "cd ${CODEBUILD_SRC_DIR}/infra/stage/scripts",
            "pip install -r requirements.txt",
            "python quota_allocation_status_updater.py",
          ],
        },
      },
    };

    const quotaAllocationStatusUpdater = new codebuild.Project(this, "QuotaAllocationStatusUpdaterProject", {
      projectName: `${stage}-quota-allocation-status-updater`,
      role: toolRole,
      buildSpec: codebuild.BuildSpec.fromObject(quotaAllocationStatusUpdaterBuildSpecObject),
      environment: {
        privileged: true,
        buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
      },
      vpc,
      source: gitHubSource,
      cache: codebuild.Cache.local(codebuild.LocalCacheMode.DOCKER_LAYER, codebuild.LocalCacheMode.CUSTOM),
      logging: {
        cloudWatch: {
          logGroup: new LogGroup(this, "QuotaAllocationStatusUpdaterLogGroup", {
            retention: RetentionDays.ONE_YEAR + RetentionDays.SIX_MONTHS,
            removalPolicy: cdk.RemovalPolicy.DESTROY,
          }),
        },
      },
    });
    new CfnSchedule(this, "QuotaAllocationStatusUpdaterSchedule", {
      name: `${stage}-quota-allocation-status-updater-schedule`,
      scheduleExpression: events.Schedule.cron({
        minute: "0",
        hour: "0",
      }).expressionString,
      scheduleExpressionTimezone: "Asia/Tokyo",
      flexibleTimeWindow: { mode: "OFF" },
      target: {
        arn: quotaAllocationStatusUpdater.projectArn,
        roleArn: new iam.Role(this, "SchedulerRole", {
          assumedBy: new iam.ServicePrincipal("scheduler.amazonaws.com"),
          inlinePolicies: {
            SchedulerPolicy: new iam.PolicyDocument({
              statements: [
                new iam.PolicyStatement({
                  actions: ["codebuild:StartBuild"],
                  resources: [quotaAllocationStatusUpdater.projectArn],
                }),
              ],
            }),
          },
        }).roleArn,
      },
      groupName: "default",
    });

    const contractProviderCreatorBuildSpecObject = {
      version: 0.2,
      env: {
        shell: "/bin/bash",
        "parameter-store": {
          USER_POOL_ID: `/${stage}/contract-user-pool-id`,
        },
        "secrets-manager": {
          POSTGRES_HOST: `${dbClusterSecretName}:host`,
          POSTGRES_PORT: `${dbClusterSecretName}:port`,
          POSTGRES_USER: `${dbClusterSecretName}:username`,
          POSTGRES_PASSWORD: `${dbClusterSecretName}:password`,
          POSTGRES_DB: `${dbClusterSecretName}:dbname`,
        },
      },
      phases: {
        build: {
          commands: [
            "cd ${CODEBUILD_SRC_DIR}/backend",
            "pip install -r requirements.txt",
            "python -m src.tools.contract_provider_creator --name $NAME",
          ],
        },
      },
    };

    new codebuild.Project(this, "ContractProviderCreatorProject", {
      projectName: `${stage}-contract-provider-creator`,
      role: toolRole,
      buildSpec: codebuild.BuildSpec.fromObject(contractProviderCreatorBuildSpecObject),
      environment: {
        privileged: true,
        buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
      },
      environmentVariables: {
        NAME: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
      },
      vpc,
      source: gitHubSource,
      cache: codebuild.Cache.local(codebuild.LocalCacheMode.DOCKER_LAYER, codebuild.LocalCacheMode.CUSTOM),
      logging: {
        cloudWatch: {
          logGroup: new LogGroup(this, "ContractProviderCreatorLogGroup", {
            retention: RetentionDays.ONE_YEAR + RetentionDays.SIX_MONTHS,
            removalPolicy: cdk.RemovalPolicy.DESTROY,
          }),
        },
      },
    });

    const managementConsoleInitializerBuildSpecObject = {
      version: 0.2,
      env: {
        shell: "/bin/bash",
        "parameter-store": {
          MANAGEMENT_USER_POOL_ID: `/${stage}/management-user-pool-id`,
        },
        "secrets-manager": {
          POSTGRES_HOST: `${dbClusterAppSecretName}:host`,
          POSTGRES_PORT: `${dbClusterAppSecretName}:port`,
          POSTGRES_USER: `${dbClusterAppSecretName}:username`,
          POSTGRES_PASSWORD: `${dbClusterAppSecretName}:password`,
          POSTGRES_DB: `${dbClusterAppSecretName}:dbname`,
        },
      },
      phases: {
        build: {
          commands: [
            "cd ${CODEBUILD_SRC_DIR}/backend",
            "pip install -r requirements.txt",
            'python -m src.tools.management_console_initializer --whi-customer-ids "$WHI_CUSTOMER_IDS" --cydas-customer-ids "$CYDAS_CUSTOMER_IDS" --tenant-name "$TENANT_NAME" --user-emails "$USER_EMAILS"',
          ],
        },
      },
    };

    new codebuild.Project(this, "ManagementConsoleInitializerProject", {
      projectName: `${stage}-management-console-initializer`,
      role: toolRole,
      buildSpec: codebuild.BuildSpec.fromObject(managementConsoleInitializerBuildSpecObject),
      environment: {
        privileged: true,
        buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
      },
      environmentVariables: {
        WHI_CUSTOMER_IDS: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
        CYDAS_CUSTOMER_IDS: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
        TENANT_NAME: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
        USER_EMAILS: {
          type: codebuild.BuildEnvironmentVariableType.PLAINTEXT,
          value: "",
        },
      },
      vpc,
      source: gitHubSource,
      cache: codebuild.Cache.local(codebuild.LocalCacheMode.DOCKER_LAYER, codebuild.LocalCacheMode.CUSTOM),
      logging: {
        cloudWatch: {
          logGroup: new LogGroup(this, "ManagementConsoleInitializerLogGroup", {
            retention: RetentionDays.EIGHTEEN_MONTHS,
            removalPolicy: cdk.RemovalPolicy.DESTROY,
          }),
        },
      },
    });
  }
}
