resource "aws_route53_zone" "my_hosted_zone" {
  name = var.domain_name
}

# Request an SSL certificate for the domain
resource "aws_acm_certificate" "my_certificate_request" {
  provider                  = aws.aws_use1
  domain_name               = "*.${var.domain_name}"
  validation_method         = "DNS"

  tags = {
    Name : var.domain_name
  }

  lifecycle {
    create_before_destroy = true
  }
}

# Create a DNS record to prove that we own the domain
# for)each syntax as discussed here: 
# https://github.com/hashicorp/terraform-provider-aws/issues/10098#issuecomment-663562342
resource "aws_route53_record" "my_validation_record" {
  zone_id = aws_route53_zone.my_hosted_zone.zone_id
  for_each = {
    for dvo in aws_acm_certificate.my_certificate_request.domain_validation_options: dvo.domain_name => {
      name   = dvo.resource_record_name
      record = dvo.resource_record_value
      type   = dvo.resource_record_type
    }
  }
  name    = each.value.name
  records = [each.value.record]
  type    = each.value.type
  ttl     = 60
}

resource "aws_acm_certificate_validation" "my_certificate_validation" {
  provider            = aws.aws_use1
  certificate_arn         = aws_acm_certificate.my_certificate_request.arn
  validation_record_fqdns = [for record in aws_route53_record.my_validation_record: record.fqdn]
}

resource "aws_route53_record" "my_caa_record" {
  zone_id = aws_route53_zone.my_hosted_zone.zone_id
  name    = var.domain_name
  type    = "CAA"
  records = [
    "0 issue \"amazon.com\"",
    "0 issuewild \"amazon.com\""
  ]
  ttl = 60
}

# Store the certificate in SSM so that we can access it from other resources
resource "aws_ssm_parameter" "certificate_arn" {
  name  = "/ssl_certificate_arn"
  type  = "String"
  value = aws_acm_certificate.my_certificate_request.arn
}