import * as iam from 'aws-cdk-lib/aws-iam';
import { Construct } from 'constructs';
import * as events from 'aws-cdk-lib/aws-events';
import * as targets from 'aws-cdk-lib/aws-events-targets';
import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import { config } from '../../config';
import * as secretsmanager from 'aws-cdk-lib/aws-secretsmanager';
import * as s3 from 'aws-cdk-lib/aws-s3';

export interface AddMobileV4GensProps extends cdk.StackProps {
  accountStage: string;
}

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

    const vpc = ec2.Vpc.fromLookup(this, 'SunoMainVpc', {
      vpcId: config[`${props.accountStage}`].vpc,
    });

    // Import the external layer by ARN
    const externalLayer = lambda.LayerVersion.fromLayerVersionArn(
      this,
      'ImportedLayer',
      'arn:aws:lambda:us-east-2:770693421928:layer:Klayers-p312-psycopg:7'
    );

    // Create Lambda layer with dependencies
    const layerFromRequirement = new lambda.LayerVersion(this, 'DatabaseMonitorReqDependences', {
      code: lambda.Code.fromAsset('lambda/glue-jobs/layers', {
        bundling: {
          image: lambda.Runtime.PYTHON_3_12.bundlingImage,
          command: ['bash', '-c', 'pip install -r requirements.txt -t /asset-output/python && ' + 'cp requirements.txt /asset-output/'],
        },
      }),
      compatibleRuntimes: [lambda.Runtime.PYTHON_3_12],
      description: 'Lambda layer with Python dependencies',
    });

    const lambdaFunction = new lambda.Function(this, 'addFreeV4GensDBUpdater', {
      runtime: lambda.Runtime.PYTHON_3_12,
      handler: 'add-mobile-v4-gens-db-update.handler',
      code: lambda.Code.fromAsset('lambda/add-mobile-v4-gens-db-update'),
      functionName: 'addFreeV4GensDBUpdater',
      timeout: cdk.Duration.minutes(15),
      layers: [externalLayer, layerFromRequirement],
      memorySize: 1024,
      vpc: vpc,
      environment: {
        env: props.accountStage,
      },
    });

    const secret = secretsmanager.Secret.fromSecretNameV2(this, 'dbsecret', `studio-api-${props.accountStage}-envs`);
    secret.grantRead(lambdaFunction);
  }
}
