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


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

export class MaxMindStack extends cdk.Stack {

  constructor(scope: Construct, id: string, props: MaxMindStackProps) {
    super(scope, id, props);
        // Define the Lambda Function
        const maxmindDownloadLambda = CreateMaxMindDBDownloadLambda(this, props.accountStage);

        // Create a CloudWatch Events rule to trigger the Lambda function every Wednesday at 12:00 pm UTC
        const rule = new events.Rule(this, 'MaxmindDownloadScheduleRule', {
            schedule: events.Schedule.cron({ minute: '0', hour: '12', weekDay: '4' }),
            ruleName: 'MaxmindDownloadScheduleRule',
        });

        // Define the payload to send to the Lambda function
        const scheduledMaxmindDownloadEventPayload = {
            body: JSON.stringify({ sentence: "Scheduled invocation" })
        };
  
        // Add the Lambda function alias as the target of the rule with the specified payload
        rule.addTarget(new targets.LambdaFunction(maxmindDownloadLambda, {
            event: events.RuleTargetInput.fromObject(scheduledMaxmindDownloadEventPayload)
        }));
        
        // Add the Lambda function to put objects in the S3 bucket
        const existingBucket = s3.Bucket.fromBucketName(this, 'ExistingBucket', 'suno-prod-maxmind-database');
        existingBucket.grantPut(maxmindDownloadLambda);

        // Add the Lambda function to get the secret from AWS Secrets Manager
        const secret = secretsmanager.Secret.fromSecretNameV2(this, 'MySecret', 'maxmind-curl-account-and-key');
        secret.grantRead(maxmindDownloadLambda);

        // Grant CloudWatch Events permission to invoke the Lambda function
        maxmindDownloadLambda.addPermission('AllowCloudWatchInvoke', {
            principal: new iam.ServicePrincipal('events.amazonaws.com'),
            action: 'lambda:InvokeFunction',
            sourceArn: rule.ruleArn,
        });
  }
}