# Aurora MySQL for Coda persistent conversation DB.
# Mirrors the royalty_accounting pattern with binlog enabled for future Fivetran CDC.

resource "aws_rds_cluster_parameter_group" "coda_cluster_parameter_group" {
  name        = "${var.environment}-${var.service_name}-mysql8-cluster-parameter-group"
  family      = "aurora-mysql8.0"
  description = "${var.environment}-${var.service_name}-mysql8-cluster-parameter-group"

  parameter {
    apply_method = "pending-reboot"
    name         = "binlog_format"
    value        = "ROW"
  }
}

module "ows_coda_rds" {
  source = "git@github.com:theorchard/terraform-rds.git//?ref=8.0.0"

  providers = {
    aws.dns = aws.networking
  }

  environment        = var.environment
  service_name       = var.service_name
  application_family = var.application_family

  # Engine
  rds_engine         = "aurora-mysql"
  rds_engine_version = "8.0"

  # Instance sizing — db.r6g.large for prod (matches royalty_accounting)
  rds_cluster_instance_class = "db.r6g.large"
  rds_cluster_instance_count = "2"

  # Credentials — initial value only; rotated out-of-band via generic-engineer-role.
  rds_master_username = "coda_admin"
  rds_master_password = "ReplaceThisWithASecurePassword123!"

  # Parameter groups
  rds_db_cluster_parameter_group_name       = aws_rds_cluster_parameter_group.coda_cluster_parameter_group.name
  rds_cluster_instance_parameter_group_name = "default.aurora-mysql8.0"

  # Networking — AZs omitted; Aurora auto-selects from the DB subnet group.
  # Hardcoding AZs fails when specific AZs have transient capacity constraints.
  vpc_id            = module.vpc_info.vpc_id
  rds_db_subnet_ids = module.vpc_info.default_private_subnet_ids

  # Security
  custom_kms_key_enabled        = true
  rds_ingress_prefix_list_names = ["shared-orcd-jump-box-private-subnet-prefix-list"]
  rds_ingress_security_groups = [
    module.ows_coda_fargate_environment.fargate_security_group_id,
  ]

  # Monitoring
  rds_performance_insights_enabled = true

  # DNS
  route53_record_creation_enabled = true
}

module "ows_coda_rds_dashboard" {
  source = "git@github.com:theorchard/terraform-datadog.git//modules/rds?ref=6.18.1"

  environment        = var.environment
  service_name       = var.service_name
  application_family = var.application_family
  teams              = ["coda-${var.environment}"]

  notification_endpoints            = local.datadog_notification_endpoints
  escalation_notification_endpoints = local.datadog_escalation_notification_endpoints
}
