locals {
  iam_auth = var.iam_auth ? "REQUIRED" : "DISABLED"
}

resource "aws_db_proxy" "this" {
  name                   = var.name
  debug_logging          = var.debug_logging
  engine_family          = var.engine_family
  idle_client_timeout    = var.idle_client_timeout
  require_tls            = var.require_tls
  role_arn               = var.rds_proxy_role_arn
  vpc_security_group_ids = var.vpc_security_group_ids
  vpc_subnet_ids         = var.vpc_subnet_ids

  dynamic "auth" {
    for_each = var.creds_secrets
    content {
      auth_scheme = "SECRETS"
      iam_auth    = local.iam_auth
      secret_arn  = auth.value
    }
  }

  tags = merge(var.tags, { "Name" = var.name })
}

resource "aws_db_proxy_default_target_group" "this" {
  db_proxy_name = aws_db_proxy.this.name

  connection_pool_config {
    connection_borrow_timeout    = var.connection_borrow_timeout
    init_query                   = var.init_query
    max_connections_percent      = var.max_connections_percent
    max_idle_connections_percent = var.max_idle_connections_percent
    session_pinning_filters      = var.session_pinning_filters
  }
}

resource "aws_db_proxy_target" "this" {
  db_instance_identifier = var.db_instance_id
  db_cluster_identifier  = var.db_cluster_id
  db_proxy_name          = aws_db_proxy.this.name
  target_group_name      = aws_db_proxy_default_target_group.this.name
}

// only for Aurora clusters
resource "aws_db_proxy_endpoint" "this" {
  count                  = var.db_cluster_id != null && var.read_only_endpoint_enabled ? 1 : 0
  db_proxy_name          = aws_db_proxy.this.name
  db_proxy_endpoint_name = "${var.name}-ro"
  vpc_subnet_ids         = var.vpc_subnet_ids
  vpc_security_group_ids = var.vpc_security_group_ids
  target_role            = "READ_ONLY"
}
