# Adapt the references to your existing pool, tested Lambda functions, and KMS key.
# Declare hashicorp/null in your required providers.
# Preserve every existing LambdaConfig entry and all updateable pool settings.

variable "aws_region" {
  type = string
}

variable "cognito_pool_update" {
  description = "Reviewed complete UpdateUserPool settings, excluding UserPoolId and LambdaConfig."
  type        = any
}

locals {
  existing_lambda_config = {
    PreSignUp          = aws_lambda_function.presignup.arn
    PostConfirmation   = aws_lambda_function.post_confirmation.arn
    PostAuthentication = aws_lambda_function.post_authentication.arn
    CustomEmailSender = {
      LambdaArn     = aws_lambda_function.email_sender.arn
      LambdaVersion = "V1_0"
    }
    KMSKeyID = aws_kms_key.cognito_email.arn
  }

  pool_update_json = jsonencode(merge(var.cognito_pool_update, {
    UserPoolId = aws_cognito_user_pool.main.id
    LambdaConfig = merge(local.existing_lambda_config, {
      InboundFederation = {
        LambdaArn     = aws_lambda_function.inbound_federation.arn
        LambdaVersion = "V1_0"
      }
    })
  }))
}

resource "aws_lambda_permission" "inbound_federation" {
  statement_id   = "AllowCognitoInboundFederation"
  action         = "lambda:InvokeFunction"
  function_name  = aws_lambda_function.inbound_federation.function_name
  principal      = "cognito-idp.amazonaws.com"
  source_arn     = aws_cognito_user_pool.main.arn
  source_account = data.aws_caller_identity.current.account_id
}

data "aws_caller_identity" "current" {}

resource "null_resource" "inbound_federation" {
  triggers = {
    pool_id         = aws_cognito_user_pool.main.id
    request_hash    = sha256(local.pool_update_json)
    region          = var.aws_region
    script_revision = "1"
  }

  provisioner "local-exec" {
    interpreter = ["/bin/sh", "-c"]
    environment = {
      COGNITO_UPDATE_JSON = local.pool_update_json
      COGNITO_REGION      = var.aws_region
    }
    command = <<-EOT
      set -eu
      umask 077
      request=$(mktemp)
      trap 'rm -f "$request"' 0
      printf '%s' "$COGNITO_UPDATE_JSON" > "$request"
      aws cognito-idp update-user-pool \
        --region "$COGNITO_REGION" \
        --cli-input-json "file://$request" \
        --no-cli-pager
    EOT
  }

  depends_on = [aws_lambda_permission.inbound_federation]
}
