Parameters:

  VPC:
    Type: String
    Description: Enter VPC


  PublicSubnet1:
    Description: PrivateSubnet1 shared from account 
    Type: String

  PublicSubnet2:
    Description: PrivateSubnet2 shared from account 
    Type: String

Resources:
      
  PublicLoadBalancerSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: "URL-Shortener-ALB-SG"    
      GroupDescription: "Access to the public facing load balancer"
      VpcId: !Ref VPC
      SecurityGroupIngress:
        - CidrIp: 0.0.0.0/0
          IpProtocol: -1

  urlshortenerlb:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Name: "urlshortenerlb"
      Scheme: internet-facing
      LoadBalancerAttributes:
        - Key: idle_timeout.timeout_seconds
          Value: "30"
      Subnets:
        - !Ref PublicSubnet1
        - !Ref PublicSubnet2
      SecurityGroups:
        - !Ref PublicLoadBalancerSecurityGroup

  urlshortenertg:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      HealthCheckIntervalSeconds: 30
      HealthCheckPath: /
      HealthCheckProtocol: HTTP
      HealthCheckTimeoutSeconds: 5
      HealthyThresholdCount: 5
      TargetType: ip
      Name: "urlshortenertg"
      Port: 80
      Protocol: HTTP
      UnhealthyThresholdCount: 2
      TargetGroupAttributes:
        - Key: deregistration_delay.timeout_seconds
          Value: 120
      VpcId: !Ref VPC
      
      
  urlshortenerlistener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      DefaultActions:
        - Type: forward
          TargetGroupArn: !Ref urlshortenertg
      LoadBalancerArn: !Ref urlshortenerlb
      Port: 80
      Protocol: HTTP


Outputs:
  ALBOutput:
    Value: !GetAtt urlshortenerlb.DNSName
    Export:
      Name: "URLShortener-LB-Endpoint"
  TargetGroupOutput:
    Value: !Ref urlshortenertg
    Export:
      Name: "URLShortener-TargetGroup-ARN"
  ListenerARN:
    Value: !Ref urlshortenerlistener
    Export:
      Name: "URLShortener-Listener-ARN"