import * as cdk from "aws-cdk-lib";
import * as backup from "aws-cdk-lib/aws-backup";
import * as kms from "aws-cdk-lib/aws-kms";
import { Construct } from "constructs";
import { Context } from "../lib/context";

interface StackProps extends cdk.StackProps {
  stage: string;
  backupProps: Context["backupProps"];
}

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

    const key = new kms.Key(this, "BackupKey", {
      alias: `${stage}-backup-vault-key`,
      description: "Key for backup encryption",
      removalPolicy: cdk.RemovalPolicy.DESTROY,
    });
    const vault = new backup.BackupVault(this, "BackupVault", {
      backupVaultName: `${stage}-backup-vault`,
      encryptionKey: key,
      removalPolicy: cdk.RemovalPolicy.DESTROY,
    });

    const plan = new backup.BackupPlan(this, "Plan", {
      backupPlanName: `${stage}-backup-plan`,
      backupVault: vault,
    });
    plan.addRule(
      new backup.BackupPlanRule({
        ruleName: `${stage}-daily-backup`,
        scheduleExpression: cdk.aws_events.Schedule.cron({ minute: "0", hour: "6" }),
        deleteAfter: backupProps.backupRetentionDays,
        backupVault: vault,
        enableContinuousBackup: true,
      })
    );
    new backup.BackupSelection(this, "Selection", {
      backupPlan: plan,
      resources: [backup.BackupResource.fromTag("Project", stage)],
      backupSelectionName: `${stage}-backup-selection`,
      allowRestores: true,
    });
  }
}
