{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Lambda Function resource stack creation using Amplify CLI",
    "Parameters": {
        "deploymentBucketName": {
            "Type": "String"
        },
        "env": {
            "Type": "String"
        },
        "s3Key": {
            "Type": "String"
        },
        "reactAppOpenaiApiKey": {
            "Type": "String"
        }
    },
    "Conditions": {
        "ShouldNotCreateEnvResources": {
            "Fn::Equals": [
                {
                    "Ref": "env"
                },
                "NONE"
            ]
        }
    },
    "Resources": {
        "LambdaFunction": {
          "Type": "AWS::Lambda::Function",
          "Metadata": {
            "aws:asset:path": "./src",
            "aws:asset:property": "Code"
          },
          "Properties": {
            "Code": {
                "S3Bucket": {
                    "Ref": "deploymentBucketName"
                },
                "S3Key": {
                    "Ref": "s3Key"
                }
            },
            "Handler": "index.handler",
            "FunctionName": {
                "Fn::If": [
                    "ShouldNotCreateEnvResources",
                    "openAIFileProcessing",
                    {
                        "Fn::Join": [
                            "",
                            [
                                "openAIFileProcessing",
                                "-",
                                {
                                    "Ref": "env"
                                }
                            ]
                        ]
                    }
                ]
            },
            "Environment": {
                "Variables" : {"ENV":{"Ref":"env"},"REGION":{"Ref":"AWS::Region"},"REACT_APP_OPENAI_API_KEY":{"Ref":"reactAppOpenaiApiKey"}}
            },
            "Role": { "Fn::GetAtt": ["LambdaExecutionRole", "Arn"] },
            "Runtime": "nodejs16.x",
            "Layers": [],
            "Timeout": 25
          }
        },
        "EventBridgeRule": {
            "Type": "AWS::Events::Rule",
            "Properties": {
                "Name": {
                    "Fn::If": [
                        "ShouldNotCreateEnvResources",
                        "openAIFileProcessing-schedule",
                        {
                            "Fn::Join": [
                                "",
                                [
                                    "openAIFileProcessing-schedule",
                                    "-",
                                    {
                                        "Ref": "env"
                                    }
                                ]
                            ]
                        }
                    ]
                },
                "ScheduleExpression": "rate(1 minute)",
                "State": "ENABLED",
                "Targets": [
                    {
                        "Arn": { "Fn::GetAtt": ["LambdaFunction", "Arn"] },
                        "Id": "TargetFunction"
                    }
                ]
            }
        },
        "LambdaEventBridgePermission": {
            "Type": "AWS::Lambda::Permission",
            "Properties": {
                "Action": "lambda:InvokeFunction",
                "FunctionName": { "Ref": "LambdaFunction" },
                "Principal": "events.amazonaws.com",
                "SourceArn": { "Fn::GetAtt": ["EventBridgeRule", "Arn"] }
            }
        },
        "ApiGatewayRestApi": {
            "Type": "AWS::ApiGateway::RestApi",
            "Properties": {
                "Name": {
                    "Fn::If": [
                        "ShouldNotCreateEnvResources",
                        "openAIProcessingApi",
                        {
                            "Fn::Join": [
                                "",
                                [
                                    "openAIProcessingApi",
                                    "-",
                                    {
                                        "Ref": "env"
                                    }
                                ]
                            ]
                        }
                    ]
                },
                "Description": "API Gateway for invoking openAIFileProcessing Lambda function",
                "BinaryMediaTypes": ["*/*"]
            }
        },
        "ApiGatewayResource": {
            "Type": "AWS::ApiGateway::Resource",
            "Properties": {
                "RestApiId": { "Ref": "ApiGatewayRestApi" },
                "ParentId": { "Fn::GetAtt": ["ApiGatewayRestApi", "RootResourceId"] },
                "PathPart": "openaiprocess"
            }
        },
        "ApiGatewayMethod": {
            "Type": "AWS::ApiGateway::Method",
            "Properties": {
                "RestApiId": { "Ref": "ApiGatewayRestApi" },
                "ResourceId": { "Ref": "ApiGatewayResource" },
                "HttpMethod": "POST",
                "AuthorizationType": "AWS_IAM",
                "Integration": {
                    "Type": "AWS_PROXY",
                    "IntegrationHttpMethod": "POST",
                    "Uri": {
                        "Fn::Join": [
                            "",
                            [
                                "arn:aws:apigateway:",
                                { "Ref": "AWS::Region" },
                                ":lambda:path/2015-03-31/functions/",
                                { "Fn::GetAtt": ["LambdaFunction", "Arn"] },
                                "/invocations"
                            ]
                        ]
                    },
                    "IntegrationResponses": [
                        {
                            "StatusCode": "200",
                            "ResponseParameters": {
                                "method.response.header.Access-Control-Allow-Origin": "'*'"
                            }
                        }
                    ]
                },
                "MethodResponses": [
                    {
                        "StatusCode": "200",
                        "ResponseParameters": {
                            "method.response.header.Access-Control-Allow-Origin": true
                        }
                    }
                ]
            }
        },
        "ApiGatewayMethodOptions": {
            "Type": "AWS::ApiGateway::Method",
            "Properties": {
                "RestApiId": { "Ref": "ApiGatewayRestApi" },
                "ResourceId": { "Ref": "ApiGatewayResource" },
                "HttpMethod": "OPTIONS",
                "AuthorizationType": "AWS_IAM",
                "Integration": {
                    "Type": "MOCK",
                    "IntegrationResponses": [
                        {
                            "StatusCode": "200",
                            "ResponseParameters": {
                                "method.response.header.Access-Control-Allow-Headers": "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,Accept'",
                                "method.response.header.Access-Control-Allow-Methods": "'OPTIONS,POST'",
                                "method.response.header.Access-Control-Allow-Origin": "'*'"
                            },
                            "ResponseTemplates": {
                                "application/json": "{}"
                            }
                        }
                    ],
                    "RequestTemplates": {
                        "application/json": "{\"statusCode\": 200}"
                    }
                },
                "MethodResponses": [
                    {
                        "StatusCode": "200",
                        "ResponseParameters": {
                            "method.response.header.Access-Control-Allow-Headers": true,
                            "method.response.header.Access-Control-Allow-Methods": true,
                            "method.response.header.Access-Control-Allow-Origin": true
                        }
                    }
                ]
            }
        },
        "ApiGatewayCorsResource": {
            "Type": "AWS::ApiGateway::Resource",
            "Properties": {
                "RestApiId": { "Ref": "ApiGatewayRestApi" },
                "ParentId": { "Fn::GetAtt": ["ApiGatewayRestApi", "RootResourceId"] },
                "PathPart": "{cors+}"
            }
        },
        "ApiGatewayCorsMethod": {
            "Type": "AWS::ApiGateway::Method",
            "Properties": {
                "RestApiId": { "Ref": "ApiGatewayRestApi" },
                "ResourceId": { "Ref": "ApiGatewayCorsResource" },
                "HttpMethod": "OPTIONS",
                "AuthorizationType": "AWS_IAM",
                "Integration": {
                    "Type": "MOCK",
                    "IntegrationResponses": [
                        {
                            "StatusCode": "200",
                            "ResponseParameters": {
                                "method.response.header.Access-Control-Allow-Headers": "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,Accept'",
                                "method.response.header.Access-Control-Allow-Methods": "'OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD'",
                                "method.response.header.Access-Control-Allow-Origin": "'*'"
                            },
                            "ResponseTemplates": {
                                "application/json": "{}"
                            }
                        }
                    ],
                    "RequestTemplates": {
                        "application/json": "{\"statusCode\": 200}"
                    }
                },
                "MethodResponses": [
                    {
                        "StatusCode": "200",
                        "ResponseParameters": {
                            "method.response.header.Access-Control-Allow-Headers": true,
                            "method.response.header.Access-Control-Allow-Methods": true,
                            "method.response.header.Access-Control-Allow-Origin": true
                        }
                    }
                ]
            }
        },
        "ApiGatewayDeployment": {
            "Type": "AWS::ApiGateway::Deployment",
            "DependsOn": ["ApiGatewayMethod", "ApiGatewayMethodOptions", "ApiGatewayCorsMethod"],
            "Properties": {
                "RestApiId": { "Ref": "ApiGatewayRestApi" },
                "StageName": "prod"
            }
        },
        "LambdaApiGatewayPermission": {
            "Type": "AWS::Lambda::Permission",
            "Properties": {
                "Action": "lambda:InvokeFunction",
                "FunctionName": { "Ref": "LambdaFunction" },
                "Principal": "apigateway.amazonaws.com",
                "SourceArn": {
                    "Fn::Join": [
                        "",
                        [
                            "arn:aws:execute-api:",
                            { "Ref": "AWS::Region" },
                            ":",
                            { "Ref": "AWS::AccountId" },
                            ":",
                            { "Ref": "ApiGatewayRestApi" },
                            "/*"
                        ]
                    ]
                }
            }
        },
        "LambdaExecutionRole": {
            "Type": "AWS::IAM::Role",
            "Properties": {
                "RoleName": {
                    "Fn::If": [
                        "ShouldNotCreateEnvResources",
                        "bigpondLambdaRole4fc1cb86",
                        {
                            "Fn::Join": [
                                "",
                                [
                                    "bigpondLambdaRole4fc1cb86",
                                    "-",
                                    {
                                        "Ref": "env"
                                    }
                                ]
                            ]
                        }
                    ]
                },
                "AssumeRolePolicyDocument": {
                    "Version": "2012-10-17",
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Principal": {
                                "Service": [
                                    "lambda.amazonaws.com"
                                ]
                            },
                            "Action": [
                                "sts:AssumeRole"
                            ]
                        }
                    ]
                }
            }
        },
        "lambdaexecutionpolicy": {
            "DependsOn": ["LambdaExecutionRole"],
            "Type": "AWS::IAM::Policy",
            "Properties": {
                "PolicyName": "lambda-execution-policy",
                "Roles": [{ "Ref": "LambdaExecutionRole" }],
                "PolicyDocument": {
                    "Version": "2012-10-17",
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Action": ["logs:CreateLogGroup",
                            "logs:CreateLogStream",
                            "logs:PutLogEvents"],
                            "Resource": { "Fn::Sub": [ "arn:aws:logs:${region}:${account}:log-group:/aws/lambda/${lambda}:log-stream:*", { "region": {"Ref": "AWS::Region"}, "account": {"Ref": "AWS::AccountId"}, "lambda": {"Ref": "LambdaFunction"}} ]}
                        }
                    ]
                }
            }
        }
    },
    "Outputs": {
        "Name": {
            "Value": {
                "Ref": "LambdaFunction"
            }
        },
        "Arn": {
            "Value": {"Fn::GetAtt": ["LambdaFunction", "Arn"]}
        },
        "Region": {
            "Value": {
                "Ref": "AWS::Region"
            }
        },
        "LambdaExecutionRole": {
            "Value": {
                "Ref": "LambdaExecutionRole"
            }
        },
        "EventBridgeRuleArn": {
            "Value": {
                "Fn::GetAtt": ["EventBridgeRule", "Arn"]
            }
        },
        "ApiEndpoint": {
            "Value": {
                "Fn::Join": [
                    "",
                    [
                        "https://",
                        { "Ref": "ApiGatewayRestApi" },
                        ".execute-api.",
                        { "Ref": "AWS::Region" },
                        ".amazonaws.com/prod/openaiprocess"
                    ]
                ]
            },
            "Description": "API endpoint URL for invoking the openAIFileProcessing function"
        }
    }
}