data "aws_iam_policy_document" "lambda_exec_role" {
    statement {
        effect = "Allow"
        actions = ["sts:AssumeRole"]
        principals {
            type = "Service"
            identifiers = ["lambda.amazonaws.com", "edgelambda.amazonaws.com"]
        }
    }
}

resource "aws_iam_role" "{{ env_collection.instance_name }}_lambda" {
    name = "{{ env_collection.instance_name }}-lambda"
    assume_role_policy = "${data.aws_iam_policy_document.lambda_exec_role.json}"
}

resource "aws_lambda_function" "{{ env_collection.instance_name }}_frontend_routing" {
    function_name = "{{ env_collection.instance_name }}-frontend-routing"
    publish = true
    provider = aws.us_east_1
    role = aws_iam_role.{{ env_collection.instance_name }}_lambda.arn
    handler = "index.handler"
    source_code_hash = filebase64sha256("frontend_routing_lambda.zip")
    filename = "frontend_routing_lambda.zip"
    runtime = "nodejs16.x"
}

resource "aws_cloudfront_origin_request_policy" "{{ env_collection.instance_name }}_frontend" {
  name    = "{{ env_collection.instance_name }}-frontend"
  comment = "Frontend origin request policy"
  cookies_config {
    cookie_behavior = "all"
  }
  headers_config {
    header_behavior = "none"
  }
  query_strings_config {
    query_string_behavior = "all"
  }
}

resource "aws_cloudfront_cache_policy" "{{ env_collection.instance_name }}_frontend" {
  name        = "{{ env_collection.instance_name }}-frontend"
  comment     = "Frontend cache policy"
  default_ttl = 0
  parameters_in_cache_key_and_forwarded_to_origin {
    cookies_config {
      cookie_behavior = "all"
    }
    headers_config {
      header_behavior = "none"
    }
    query_strings_config {
      query_string_behavior = "all"
    }
  }
}
