import * as cdk from 'aws-cdk-lib';
import * as elbv2 from 'aws-cdk-lib/aws-elasticloadbalancingv2';
import { IVpc } from 'aws-cdk-lib/aws-ec2';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import { Construct } from 'constructs';
import { certificate } from '../certificate/studio-api-certificate'; // Import the certificate
import * as certManager from 'aws-cdk-lib/aws-certificatemanager';

export const setupLoadBalancer = (scope: Construct, vpc: IVpc, subnets: ec2.ISubnet[], certificate: certManager.ICertificate) => {
  // Create a security group for the load balancer
  const loadBalancerSecurityGroup = new ec2.SecurityGroup(scope, 'LoadBalancerSG', {
    vpc: vpc,
    allowAllOutbound: true,
    description: 'BackendInfraStack/LoadBalancerSG',
  });

  loadBalancerSecurityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(80), 'Allow HTTP traffic');

  // Allow HTTPS traffic on port 443
  loadBalancerSecurityGroup.addIngressRule(ec2.Peer.anyIpv4(), ec2.Port.tcp(443), 'Allow HTTPS traffic');

  const loadBalancer = new elbv2.ApplicationLoadBalancer(scope, 'LoadBalancer', {
    vpc,
    vpcSubnets: {
      subnets: subnets,
    },
    internetFacing: false,
    securityGroup: loadBalancerSecurityGroup,
  });

  const blueTargetGroup = new elbv2.ApplicationTargetGroup(scope, 'BlueTargetGroup', {
    vpc,
    port: 8005,
    protocol: elbv2.ApplicationProtocol.HTTP,
    targetType: elbv2.TargetType.IP,
    healthCheck: {
      path: '/health/',
      interval: cdk.Duration.seconds(30),
      timeout: cdk.Duration.seconds(5),
      healthyThresholdCount: 2,
      unhealthyThresholdCount: 2,
    },
  });

  const greenTargetGroup = new elbv2.ApplicationTargetGroup(scope, 'GreenTargetGroup', {
    vpc,
    port: 8005,
    protocol: elbv2.ApplicationProtocol.HTTP,
    targetType: elbv2.TargetType.IP,
    healthCheck: {
      path: '/health/',
      interval: cdk.Duration.seconds(30),
      timeout: cdk.Duration.seconds(5),
      healthyThresholdCount: 2,
      unhealthyThresholdCount: 2,
    },
  });

  // Add listener for HTTP (port 80) and redirect to HTTPS
  const httpListener = loadBalancer.addListener('HttpListener', {
    port: 80,
    // defaultAction: elbv2.ListenerAction.redirect({
    //     protocol: 'HTTPS',
    //     port: '443',
    //     permanent: true,
    // }),
    defaultTargetGroups: [blueTargetGroup],
  });

  // return { loadBalancer, blueTargetGroup, greenTargetGroup, httpsListener, loadBalancerSecurityGroup };
  return { loadBalancer, blueTargetGroup, greenTargetGroup, httpListener, loadBalancerSecurityGroup };
};
