#Certificate 
resource "aws_acm_certificate" "cert_elastic" {
  count             = var.alsi_elastic_alb ? 1 : 0
  domain_name       = "${var.prefix}-alsi-elastic.${var.dns_info["public"]["zone"]}"
  validation_method = "DNS"

  tags = merge(var.standard_tags, var.tags)
}

resource "aws_acm_certificate_validation" "cert_elastic" {
  count                   = var.alsi_elastic_alb ? 1 : 0
  certificate_arn         = aws_acm_certificate.cert_elastic[count.index].arn
  validation_record_fqdns = [for record in aws_route53_record.cert_elastic_validation: record.fqdn]
}

resource "aws_route53_record" "cert_elastic_validation" {
  provider = aws.mdr-common-services-commercial

  # This syntax is tricky. If the bool is true, then we create the for_each map, otherwise we do an empty map.
  for_each = var.alsi_elastic_alb ? {
    for dvo in aws_acm_certificate.cert_elastic[0].domain_validation_options : dvo.domain_name => {
      name   = dvo.resource_record_name
      record = dvo.resource_record_value
      type   = dvo.resource_record_type
    } 
  } : {}

  allow_overwrite = true
  name            = each.value.name
  records         = [each.value.record]
  ttl             = 60
  type            = each.value.type
  zone_id         = var.dns_info["public"]["zone_id"]
}
