resource "aws_ses_domain_identity" "this" {
  domain = var.domain_name
}

# DKIM signing
resource "aws_ses_domain_dkim" "this" {
  domain = aws_ses_domain_identity.this.domain
}

# IAM user for SES SMTP
resource "aws_iam_user" "ses_user" {
  name = "${var.stage}-ses-user"
}

# SES configuration set for tracking events
resource "aws_ses_configuration_set" "this" {
  name = "${var.stage}-ses-config"
}

# SNS topic for SES event notifications
resource "aws_sns_topic" "ses_events" {
  name = "${var.stage}-ses-events"
}

# SES event destination for debugging
resource "aws_ses_event_destination" "sns" {
  name                   = "ses-event-destination"
  configuration_set_name = aws_ses_configuration_set.this.name
  enabled                = true

  matching_types = [
    "send",
    "bounce",
    "reject",
    "complaint",
    "delivery"
  ]

  sns_destination {
    topic_arn = aws_sns_topic.ses_events.arn
  }
}

resource "aws_iam_user_policy" "ses_send_policy" {
  name = "AllowSESSendEmail"
  user = aws_iam_user.ses_user.name

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Action = [
          "ses:SendEmail",
          "ses:SendRawEmail"
        ]
        Resource = "*"
      }
    ]
  })
}

resource "aws_iam_access_key" "ses_user" {
  user = aws_iam_user.ses_user.name
}

# Store SMTP credentials in AWS Secrets Manager
resource "aws_secretsmanager_secret" "ses_smtp" {
  name        = "${var.stage}/ses/smtp_credentials"
  description = "SMTP credentials for SES (${var.stage})"
}

resource "aws_secretsmanager_secret_version" "ses_smtp" {
  secret_id = aws_secretsmanager_secret.ses_smtp.id
  secret_string = jsonencode({
    username = aws_iam_access_key.ses_user.id
    password = aws_iam_access_key.ses_user.ses_smtp_password_v4
  })
}
