AWSTemplateFormatVersion: '2010-09-09'
Description: |
  Language Services - Security Groups Only
  Use this template to create just the security groups for an existing VPC

Parameters:
  AppName:
    Type: String
    Default: language-services
    Description: Name of the application

  Environment:
    Type: String
    Default: production
    Description: Deployment environment

  VpcId:
    Type: AWS::EC2::VPC::Id
    Description: VPC ID where security groups will be created

Resources:
  ALBSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: !Sub ${AppName}-${Environment}-alb-sg
      GroupDescription: Security group for Application Load Balancer
      VpcId: !Ref VpcId
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
          Description: HTTP access from anywhere
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: 0.0.0.0/0
          Description: HTTPS access from anywhere
      SecurityGroupEgress:
        - IpProtocol: -1
          CidrIp: 0.0.0.0/0
          Description: Allow all outbound traffic
      Tags:
        - Key: Name
          Value: !Sub ${AppName}-${Environment}-alb-sg
        - Key: Application
          Value: !Ref AppName
        - Key: Environment
          Value: !Ref Environment

  ECSSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: !Sub ${AppName}-${Environment}-ecs-sg
      GroupDescription: Security group for ECS tasks
      VpcId: !Ref VpcId
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 3000
          ToPort: 3000
          SourceSecurityGroupId: !Ref ALBSecurityGroup
          Description: Frontend access from ALB
        - IpProtocol: tcp
          FromPort: 5000
          ToPort: 5000
          SourceSecurityGroupId: !Ref ALBSecurityGroup
          Description: Backend API access from ALB
      SecurityGroupEgress:
        - IpProtocol: -1
          CidrIp: 0.0.0.0/0
          Description: Allow all outbound traffic
      Tags:
        - Key: Name
          Value: !Sub ${AppName}-${Environment}-ecs-sg
        - Key: Application
          Value: !Ref AppName
        - Key: Environment
          Value: !Ref Environment

  # Self-referencing rule for ECS tasks to communicate with each other
  ECSSecurityGroupSelfIngress:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: !Ref ECSSecurityGroup
      IpProtocol: -1
      SourceSecurityGroupId: !Ref ECSSecurityGroup
      Description: Allow ECS tasks to communicate with each other

Outputs:
  ALBSecurityGroupId:
    Description: ALB Security Group ID
    Value: !Ref ALBSecurityGroup
    Export:
      Name: !Sub ${AppName}-${Environment}-ALBSecurityGroup

  ECSSecurityGroupId:
    Description: ECS Security Group ID
    Value: !Ref ECSSecurityGroup
    Export:
      Name: !Sub ${AppName}-${Environment}-ECSSecurityGroup
