---
resources:
    {% if swagger_template %}
    ApiKey:
      Type: "AWS::ApiGateway::ApiKey"
      DependsOn:
        - ApiGateway
      Properties:
        Name: "{{_env.name}}-{{_env.stage|lower}}"
        Description: "API key for stage {{_env.stage}} of environment {{_env.name}}"
        Enabled: "true"

    ApiGateway:
        Type: AWS::Serverless::Api
        Properties:
            DefinitionUri: {{swagger_template}}
            StageName: {{_env.stage|lower}}
            {% if cache %}
            CacheClusterEnabled: True
            CacheClusterSize: "{{cache}}"
            {% endif %}
            Variables:
                {% for f in meta_functions %}
                VarRef{{f.name}}: {"Ref": "{{f.name}}"}
                {% endfor %}
    {% endif %}

    {% set default_description="SAM app" %}
    {% for f in meta_functions %}
    {{f.name}}:
        Type: AWS::Serverless::Function
        Properties:
            Handler: handler.lambda_handler
            Runtime: {{runtime}}
            CodeUri: {{lambda_function}}
            Description: "{{f.description or default_description}} ({{_env.name}}-{{_env.stage}})"
            MemorySize: {{f.memory_size}}
            Timeout: {{f.timeout}}
            {% if f.tracing %}
            Tracing: "{{f.tracing}}"
            {% endif %}
            {% if iam_actions %}
            Role:
                "Fn::GetAtt":
                    - LambdaRole
                    - Arn
            {% endif %}
            {% if env_vars %}
            Environment:
                Variables:
                    {% for name, value in env_vars.items() %}
                    {{name}}: {{value}}
                    {% endfor %}
            {% endif %}
            {% if subnet_ids and sg_ids %}
            VpcConfig:
                SubnetIds:
                {% for subnet in subnet_ids %}
                - {{subnet}}
                {% endfor %}
                SecurityGroupIds:
                {% for sg in sg_ids %}
                - {{sg}}
                {% endfor %}
            {% endif %}
            Events:
                {{f.name}}ApiEvent:
                    Type: Api
                    Properties:
                        {% if swagger_template %}
                        RestApiId: {"Ref": "ApiGateway"}
                        {% endif %}
                        Path: {{f.api_path}}
                        Method: {{f.http_method}}
                {% if f.keep_warm %}
                KeepWarm:
                    Type: Schedule
                    Properties:
                        Schedule: rate({{f.warm_rate_time}} minutes)
                        Input: '{"event_type": "keep_warm"}'
                {% endif %}

    {% endfor %}
    {% if simple_table %}
    Table{{_layer.name}}{{_env.stage}}:
        Type: AWS::Serverless::SimpleTable
        PrimaryKey:
            Name: {{simple_table_capacity.key_name}}
            Type: {{simple_table_capacity.key_type}}
        ProvisionedThroughput:
            ReadCapacityUnits: {{simple_table_capacity.read}}
            WriteCapacityUnits: {{simple_table_capacity.write}}
    {% endif %}

    {% if iam_actions %}
    LambdaRole:
        Type: "AWS::IAM::Role"
        Properties:
            AssumeRolePolicyDocument:
                Version: '2012-10-17'
                Statement:
                    - Effect: Allow
                      Principal:
                        Service: "lambda.amazonaws.com"
                      Action: "sts:AssumeRole"
            # Keep all environment role under the same path
            Path: {{ "/{}/".format(_env.name) }}
            Policies:
                - PolicyName: root
                  PolicyDocument:
                    Version: "2012-10-17"
                    Statement:
                        - Effect: Allow
                        # Permissions to access the DynamoDB secrets table
                          Action:
                            - "dynamodb:GetItem"
                          Resource: "*"
                        {% for policy in iam_actions %}
                        - Effect: Allow
                          Action:
                            - "{{policy.action}}"
                          Resource: "{{policy.resource}}"
                        {% endfor %}
    {% endif %}

    # Alarms
    {% if sns_topic %}
    {% if not sns_topic.startswith("arn:") %}
    SnsTopic:
      Type: "AWS::SNS::Topic"
      Properties:
        TopicName: {{sns_topic}}
        {% if alert_subscribers %}
        Subscription:
            {% for subscriber in alert_subscribers %}
            - Endpoint: "{{subscriber}}"
              Protocol: "email"
            {% endfor %}
        {% endif %}
    {% endif %}
    {% for f in meta_functions %}
    ThrottlingAlarm:
        Type: "AWS::CloudWatch::Alarm"
        Properties:
            AlarmDescription: "Lambda function is being throttled"
            AlarmActions:
                {% if not sns_topic.startswith("arn:") %}
                - Ref:
                    SnsTopic
                {% else %}
                - "{{sns_topic}}"
                {% endif %}
            MetricName: Throttles
            Namespace: AWS/Lambda
            Statistic: Maximum
            Period: 60
            EvaluationPeriods: 1
            Threshold: 0
            ComparisonOperator: GreaterThanThreshold
            Dimensions:
                - Name: FunctionName
                  Value:
                    Ref: {{f.name}}
    {% endfor %}
    {% endif %}
