AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  AWS SAM template to deploy grinder.js functionalities as multiple Lambda functions.

Parameters:

  TIMEZONE:
    Type: String
    Description: "The timezone to use."
    Default: "UTC"

Globals:
  Function:
    Timeout: 600
    Runtime: nodejs18.x
    Handler: index.handler
    Tracing: Active  # Enable X-Ray tracing
    Environment:
      Variables:
        TIMEZONE: !Ref TIMEZONE

Resources:

  # New Layer: Node.js External Dependencies
  NodeModulesLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: layer-node-modules
      Description: Layer containing Node.js external dependencies (e.g., aws-sdk, moment-timezone)
      ContentUri: ./layers/layer-node-modules/nodejs/
      CompatibleRuntimes:
        - nodejs18.x

  # New Layer: Database and Custom Modules
  DatabaseLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: database
      Description: Layer containing custom MongoDB models and utility modules
      ContentUri: ./layers/database/
      CompatibleRuntimes:
        - nodejs18.x


  # Layer1:
  #   Type: AWS::Serverless::LayerVersion
  #   Properties:
  #     LayerName: layer1
  #     Description: A layer for Node.js dependencies
  #     ContentUri: ./layers/layer1/
  #     CompatibleRuntimes:
  #       - nodejs18.x
  # Layer2:
  #   Type: AWS::Serverless::LayerVersion
  #   Properties:
  #     LayerName: layer2
  #     Description: A layer for Node.js dependencies
  #     ContentUri: ./layers/layer2/
  #     CompatibleRuntimes:
  #       - nodejs18.x
  LayerAWSSDKONLY:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: LayerAWSSDKONLY
      Description: A layer for Node.js dependencies
      ContentUri: ./layers/LayerAWSSDKONLY/
      CompatibleRuntimes:
        - nodejs18.x

  # TestDb:
  #   Type: AWS::Serverless::Function
  #   Properties:
  #     Handler: index.handler
  #     Policies:
  #       - AmazonDynamoDBFullAccess
  #     CodeUri: ./testdb/
  #     VpcConfig:
  #       SecurityGroupIds:
  #         - sg-003babb1267989dfa
  #       SubnetIds:
  #         - subnet-0e60752ccfc80074f
  #         - subnet-069f4c1a796c82f05
  #     Environment:
  #       Variables:
  #         MONGO_URL: "mongodb://tagmarshal-poc-data-config-nlb-3d7a4f2e6b8260e7.elb.us-east-2.amazonaws.com:27017/tagmarshal"
  
  # API Gateway with throttling configuration
  ApiGateway:
    Type: AWS::Serverless::Api
    Properties:
      StageName: prod
      EndpointConfiguration: REGIONAL
      TracingEnabled: true  # Enable X-Ray tracing
      MethodSettings:
        - ResourcePath: "/*"
          HttpMethod: "*"
          ThrottlingRateLimit: 10000  # Allow up to 5000 requests per second
          ThrottlingBurstLimit: 20000  # Burst capacity for handling spikes
  
  FixQueue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: FixProcessingQueue
      VisibilityTimeout: 120  # 5 minutes
      MessageRetentionPeriod: 1209600  # 14 days
      # FifoQueue: true
      # ContentBasedDeduplication: true
      RedrivePolicy:
        deadLetterTargetArn: !GetAtt DeadLetterQueue.Arn
        maxReceiveCount: 5
      # VisibilityTimeout: 1800
      
  DeadLetterQueue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: high-volume-dlq
      MessageRetentionPeriod: 1209600  # 14 days in seconds
      
  ApiErrorAlarm:
    Type: AWS::CloudWatch::Alarm
    Properties:
      AlarmName: ApiGateway5xxErrors
      AlarmDescription: Alarm if API Gateway returns too many 5xx errors
      MetricName: 5XXError
      Namespace: AWS/ApiGateway
      Statistic: Sum
      Period: 60
      EvaluationPeriods: 1
      Threshold: 10
      ComparisonOperator: GreaterThanThreshold
      Dimensions:
        - Name: ApiName
          Value: !Ref ApiGateway


  FixInsert:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: FixInsert/
      Handler: index.handler
      MemorySize: 512
      Timeout: 10
      Policies:
        - AmazonSQSFullAccess
      Environment:
        Variables:
          REGION: 'us-east-2'
          QUEUE_URL: !Ref FixQueue
      Events:
        APIEvent:
          Type: Api
          Properties:
            Path: /device/fix/{device_id}
            Method: POST
            RestApiId: !Ref ApiGateway
      VpcConfig:
        SecurityGroupIds:
          - sg-003babb1267989dfa
        SubnetIds:
          - subnet-0e60752ccfc80074f
          - subnet-069f4c1a796c82f05
      Layers:
        - !Ref LayerAWSSDKONLY

  GrindFunction:
    Type: AWS::Serverless::Function
    Properties:
      Timeout: 120
      ReservedConcurrentExecutions: 300  # Reserve up to 900 concurrent executions
      CodeUri: grind/
      Handler: index.handler
      MemorySize: 512
      Environment:
        Variables:
          REGION: 'us-east-2'
          QUEUE_URL: !Ref FixQueue
          mongoqrnlb: tagmarshal-poc-data-config-nlb-3d7a4f2e6b8260e7.elb.us-east-2.amazonaws.com
          # mongoqrnlb: '10.0.12.75'
      Policies:
        - AmazonDynamoDBFullAccess
        - AmazonSQSFullAccess
        - AmazonSSMFullAccess
      VpcConfig:
        SecurityGroupIds:
          - sg-003babb1267989dfa
        SubnetIds:
          - subnet-0e40cc02c21511972
          - subnet-0e60752ccfc80074f
          - subnet-069f4c1a796c82f05
      Layers:
        - !Ref NodeModulesLayer  # Updated to new layer
        - !Ref DatabaseLayer     # Updated to new layer
      Events:
        SQSEvent:
          Type: SQS
          Properties:
            Queue: !GetAtt FixQueue.Arn
            BatchSize: 10
            MaximumBatchingWindowInSeconds: 5

Outputs:

  ApiEndpoint:
    Description: "API Gateway endpoint URL"
    Value: !Sub "https://${ApiGateway}.execute-api.${AWS::Region}.amazonaws.com/prod/messages"

  FixQueue:
    Description: "URL of the SQS queue"
    Value: !Ref FixQueue

  GrindFunctionARN:
    Description: "Grind Lambda Function ARN"
    Value: !GetAtt GrindFunction.Arn

  FixInsertARN:
    Description: "FixInsert ARN"
    Value: !GetAtt FixInsert.Arn

  # HandleFixFunctionARN:
  #   Description: "HandleFix Lambda Function ARN"
  #   Value: !GetAtt HandleFixFunction.Arn

  # GetRawFixesFunctionARN:
  #   Description: "GetRawFixes Lambda Function ARN"
  #   Value: !GetAtt GetRawFixesFunction.Arn

  # TestDbARN:
  #   Description: "TestDb Lambda Function ARN"
  #   Value: !GetAtt TestDb.Arn

  # FixQueueURL:
  #   Description: "URL of the Fix Processing Queue"
  #   Value: !Ref FixQueue

  # ApiGatewayApi:
  #   Description: "URL of the ApiGatewayApi"
  #   Value: !Ref ApiGatewayApi
  
