# ── SES Email Sending ──────────────────────────────────────
# Creates SES domain identity + DKIM + SMTP IAM user when smtp_ses_domain is set.
# Outputs DNS records for manual addition to the external DNS provider.

resource "aws_ses_domain_identity" "email" {
  count  = var.smtp_ses_domain != "" ? 1 : 0
  domain = var.smtp_ses_domain
}

resource "aws_ses_domain_dkim" "email" {
  count  = var.smtp_ses_domain != "" ? 1 : 0
  domain = aws_ses_domain_identity.email[0].domain
}

# ── IAM user for SMTP credentials ─────────────────────────
# SES SMTP auth requires an IAM access key converted to SMTP password.

resource "aws_iam_user" "ses_smtp" {
  count = var.smtp_ses_domain != "" ? 1 : 0
  name  = "${local.name_prefix}-ses-smtp"
  tags  = { Name = "${local.name_prefix}-ses-smtp" }
}

locals {
  # When smtp_recipient_allowlist is non-empty, require every recipient of
  # every outbound email to be in the list. SES evaluates ses:Recipients
  # against envelope recipients including Cc/Bcc, so this catches all
  # header variants. ForAllValues:StringEquals means EVERY recipient in
  # the request must match at least one value in the allowlist — a single
  # unauthorized address rejects the entire send.
  #
  # merge() is used instead of a ternary because Terraform's type inference
  # rejects ternaries whose branches return objects with different keys.
  ses_smtp_condition_block = length(var.smtp_recipient_allowlist) > 0 ? {
    Condition = {
      "ForAllValues:StringEquals" = {
        "ses:Recipients" = var.smtp_recipient_allowlist
      }
    }
  } : {}

  ses_smtp_statement = merge(
    {
      Effect   = "Allow"
      Action   = "ses:SendRawEmail"
      Resource = "*"
    },
    local.ses_smtp_condition_block,
  )
}

resource "aws_iam_user_policy" "ses_smtp" {
  count = var.smtp_ses_domain != "" ? 1 : 0
  name  = "ses-send-email"
  user  = aws_iam_user.ses_smtp[0].name

  policy = jsonencode({
    Version   = "2012-10-17"
    Statement = [local.ses_smtp_statement]
  })
}

resource "aws_iam_access_key" "ses_smtp" {
  count = var.smtp_ses_domain != "" ? 1 : 0
  user  = aws_iam_user.ses_smtp[0].name
}

# ── SMTP credential outputs ───────────────────────────────
# Terraform's AWS provider already exposes the SES SMTP password derived from
# the IAM secret access key using AWS's documented SigV4 conversion algorithm.
# See: https://docs.aws.amazon.com/ses/latest/dg/smtp-credentials.html

locals {
  ses_smtp_access_key = var.smtp_ses_domain != "" ? aws_iam_access_key.ses_smtp[0].id : ""
  ses_smtp_password   = var.smtp_ses_domain != "" ? aws_iam_access_key.ses_smtp[0].ses_smtp_password_v4 : ""
}
