# Secrets Manager for authorizer
module "authorizer_secrets" {
  source = "git@github.com:theorchard/terraform-secrets-manager.git//?ref=1.5.1"
  for_each = toset(var.authorizer_secret_names)

  application_family = var.application_family
  environment        = var.environment
  service_name       = "${var.service_name}-authorizer"
  secret_name        = each.value
}

# IAM Policy Document for authorizer to read JIRA shared secret
data "aws_iam_policy_document" "authorizer_secrets_policy" {
  statement {
    effect = "Allow"
    actions = [
      "secretsmanager:GetSecretValue",
      "secretsmanager:DescribeSecret"
    ]
    resources = [
      for secret in module.authorizer_secrets : secret.secret_arn
    ]
  }
}

# IAM Policy for authorizer to read secret
resource "aws_iam_policy" "authorizer_secrets_policy" {
  name   = "SecretsManager-${var.environment}-${var.service_name}-authorizer"
  policy = data.aws_iam_policy_document.authorizer_secrets_policy.json
}

# Lambda Authorizer Function
module "lambda_authorizer" {
  source = "git@github.com:theorchard/terraform-lambda.git//?ref=4.3.0"

  environment                                    = var.environment
  lambda_function_timeout                        = 30
  use_container_image                            = true
  lambda_description                             = "Custom authorizer for Jira webhook API Gateway - validates X-Hub-Signature shared secret"
  lambda_name                                    = "${var.service_name}-authorizer"
  vpc_id                                         = module.vpc_info.vpc_id
  vpc_subnet_ids                                 = module.vpc_info.default_private_subnet_ids
  application_family                             = var.application_family
  lambda_function_memory_size                    = 256
  lambda_function_reserved_concurrent_executions = 25

  iam_managed_policy_attachments = [
    aws_iam_policy.authorizer_secrets_policy.arn
  ]

  lambda_function_environment_variables = {
    Environment = var.environment
  }
}
