AWSTemplateFormatVersion: '2010-09-09'
Description: ALB with ACM Cert for Zumie

Parameters:
  SubnetIdA:
    Type: AWS::EC2::Subnet::Id
    Description: Subnet A for ALB
  SubnetIdB:
    Type: AWS::EC2::Subnet::Id
    Description: Subnet B for ALB
  VpcId:
    Type: AWS::EC2::VPC::Id
    Description: VPC for ALB
  ZumieInstance:
    Type: AWS::EC2::Instance::Id
    Description: Existing Zumie EC2 instance
  ZumieSecurityGroup:
    Type: AWS::EC2::SecurityGroup::Id
    Description: Security group for Zumie/ALB
  CertificateArn:
    Type: String
    Description: ARN of the ACM certificate to use for HTTPS

Resources:
  LoadBalancer:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Type: application
      Subnets:
        - !Ref SubnetIdA
        - !Ref SubnetIdB
      SecurityGroups:
        - !Ref ZumieSecurityGroup

  TargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      Port: 3000  # Frontend port
      Protocol: HTTP
      VpcId: !Ref VpcId
      Targets:
        - Id: !Ref ZumieInstance

  LoadBalancerListenerHTTPS:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      LoadBalancerArn: !Ref LoadBalancer
      Port: 443
      Protocol: HTTPS
      Certificates:
        - CertificateArn: !Ref CertificateArn
      DefaultActions:
        - Type: forward
          TargetGroupArn: !Ref TargetGroup

  LoadBalancerListenerHTTP:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      LoadBalancerArn: !Ref LoadBalancer
      Port: 80
      Protocol: HTTP
      DefaultActions:
        - Type: redirect
          RedirectConfig:
            Protocol: HTTPS
            Port: 443
            StatusCode: HTTP_301