data "kubernetes_service_v1" "kong_svc" {
  depends_on = [module.kong-gateway]

  metadata {
    name      = "kong-kong-proxy"
    namespace = "kong"
  }

  lifecycle {
    postcondition {
      condition     = self.status == null || can(self.status.0.load_balancer.0.ingress.0.hostname)
      error_message = "can't get hostname for kong-kong-proxy"
    }
  }
}

data "aws_lb_hosted_zone_id" "lb_zone" {
  load_balancer_type = "network"
}

resource "aws_route53_record" "regional_api" {
  zone_id = local.hosted_zone_id
  name    = "${var.logical_region_name}.regional-api.${local.hosted_zone_name}"
  type    = "A"

  alias {
    # the hostname will be empty when deleting the tidbcloud region,
    # but aws_route53_record doesn't support empty value for alias target,
    # so we have to set it to some dummy value to make sure the destroy can go through.
    name                   = try(data.kubernetes_service_v1.kong_svc.status.0.load_balancer.0.ingress.0.hostname, "deleted")
    zone_id                = data.aws_lb_hosted_zone_id.lb_zone.id
    evaluate_target_health = false
  }
}

# Wait for DNS propagation after the Route53 record is created or updated.
# DNS changes can take time to propagate globally, so we pause for 5 minutes
# to reduce the chance of downstream resources failing due to unresolved DNS.
resource "time_sleep" "wait_for_dns_regional_api" {
  create_duration = "5m"

  # Re-trigger the sleep whenever the FQDN changes, ensuring propagation
  # is re-awaited if the record is updated (e.g. region rename).
  triggers = {
    dns = aws_route53_record.regional_api.fqdn
  }
}
