provider "aws" {
  region = var.aws_region
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "prod-business-solutions-terraform-state"
    key     = "prod/prod-business-solutions.theorchard.io/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

resource "aws_route53_zone" "subdomain" {
  # checkov:skip=CKV2_AWS_38: DNSSEC must be first implemented in the parent zone
  name = var.domain_name
}

resource "aws_cloudwatch_log_group" "route53_query_log_group" {
  # checkov:skip=CKV_AWS_338: keep logs for the last 30 days only
  name              = "/aws/route53/${aws_route53_zone.subdomain.name}"
  retention_in_days = 30
}

data "aws_iam_policy_document" "route53_query_logging_policy" {
  statement {
    actions = [
      "logs:CreateLogStream",
      "logs:PutLogEvents",
    ]

    resources = ["${aws_cloudwatch_log_group.route53_query_log_group.arn}:*"]

    principals {
      type        = "Service"
      identifiers = ["route53.amazonaws.com"]
    }
  }
}

resource "aws_cloudwatch_log_resource_policy" "route53_query_logging_policy" {
  policy_document = data.aws_iam_policy_document.route53_query_logging_policy.json
  policy_name     = "Route53-${aws_route53_zone.subdomain.name}-query-logging-policy"
}

resource "aws_route53_query_log" "query_log" {
  depends_on = [aws_cloudwatch_log_resource_policy.route53_query_logging_policy]

  cloudwatch_log_group_arn = aws_cloudwatch_log_group.route53_query_log_group.arn
  zone_id                  = aws_route53_zone.subdomain.zone_id
}

resource "aws_route53_record" "cname_records" {
  for_each = var.cname_records
  zone_id  = aws_route53_zone.subdomain.zone_id
  name     = each.key
  type     = "CNAME"
  ttl      = 300
  records  = each.value.records
}
