module "lambda_smf_fan_response_authorizer_sentry_project" {
  source = "git@github.com:theorchard/terraform-sentry//?ref=4.1.2"

  environment        = var.environment
  teams              = [var.environment]
  service_name       = var.smf_authorizer_service_name
  application_family = var.application_family
  platform           = "python"
}

module "lambda_smf_fan_response_authorizer" {
  source = "git@github.com:theorchard/terraform-lambda.git//?ref=4.3.0"

  environment        = var.environment
  application_family = var.application_family
  lambda_name        = var.smf_authorizer_service_name

  use_container_image                            = true
  container_image_custom_uri                     = var.fan_response_authorizer_image_uri
  lambda_description                             = "Validates Fan response request"
  vpc_enabled                                    = true
  vpc_id                                         = var.vpc_id
  vpc_subnet_ids                                 = var.vpc_subnet_ids
  datadog_enabled                                = true
  datadog_advanced_enabled                       = true
  lambda_function_reserved_concurrent_executions = 100
  lambda_function_timeout                        = 30

  lambda_function_environment_variables = {
    ENVIRONMENT    = var.environment
    SENTRY_DSN     = module.lambda_smf_fan_response_authorizer_sentry_project.sentry_key_dsn_public_output
    JWK_CLIENT_URI = var.jwk_client_uri
    TOKEN_ISSUER   = var.token_issuer
    TOKEN_AUDIENCE = var.token_audience
  }
}

module "lambda_smf_fan_response_authorizer_datadog_monitoring" {
  source = "git@github.com:theorchard/terraform-datadog.git//modules/lambda?ref=6.13.9"

  environment  = var.environment
  service_name = var.smf_authorizer_service_name
  teams        = ["kdh"]

  notification_endpoints = "@slack-kafka-data-highway-alerts"
}

resource "aws_api_gateway_authorizer" "smf_fan_response_authorizer" {
  name            = "${var.environment}-fan-response-authorizer"
  rest_api_id     = aws_api_gateway_rest_api.fan_response_rest_api.id
  authorizer_uri  = module.lambda_smf_fan_response_authorizer.lambda_invoke_arn
  identity_source = "method.request.header.Authorization"
  type            = "TOKEN"
}

resource "aws_lambda_permission" "fan_response_rest_api_authorizer_lambda_gateway_permission" {
  statement_id  = "AllowAPIGatewayInvoke"
  action        = "lambda:InvokeFunction"
  function_name = module.lambda_smf_fan_response_authorizer.lambda_arn
  principal     = "apigateway.amazonaws.com"
  source_arn    = "${aws_api_gateway_rest_api.fan_response_rest_api.execution_arn}/*"
}
