# =============================================================================
# RDS MySQL (kubestore) — ported from basic/rds and rds.yaml.
# Only provisioned when var.enable_rds = true.
#
# Differences from the CloudFormation version (by design):
# - deletion_protection defaults to false (var.rds_deletion_protection)
# - a final snapshot named "<cluster>-final" is taken on destroy instead of the
#   CF DeletionPolicy=Snapshot behavior
# - the Secrets Manager secret is deleted immediately (recovery_window = 0)
# =============================================================================

locals {
  rds_whitelist_cidr = "35.155.73.60/32"
}

resource "random_password" "rds" {
  count = var.enable_rds ? 1 : 0

  length  = 32
  special = false
}

resource "aws_db_subnet_group" "this" {
  count = var.enable_rds ? 1 : 0

  name        = "${local.cluster_name}-subnet-group"
  description = "Subnet group for ${local.cluster_name}"
  subnet_ids  = module.vpc.private_subnets

  tags = merge(local.common_tags, {
    Name = "${local.cluster_name}-subnet-group"
  })
}

resource "aws_security_group" "rds" {
  count = var.enable_rds ? 1 : 0

  name        = "${local.cluster_name}-sg"
  description = "Security group for ${local.cluster_name} RDS instance"
  vpc_id      = module.vpc.vpc_id

  tags = merge(local.common_tags, {
    Name = "${local.cluster_name}-sg"
  })
}

resource "aws_vpc_security_group_ingress_rule" "rds_from_eks" {
  count = var.enable_rds ? 1 : 0

  security_group_id            = aws_security_group.rds[0].id
  referenced_security_group_id = module.eks.cluster_security_group_id
  ip_protocol                  = "tcp"
  from_port                    = 3306
  to_port                      = 3306
  description                  = "Allow MySQL access from EKS cluster nodes and pods"
}

resource "aws_vpc_security_group_ingress_rule" "rds_from_whitelist" {
  count = var.enable_rds ? 1 : 0

  security_group_id = aws_security_group.rds[0].id
  cidr_ipv4         = local.rds_whitelist_cidr
  ip_protocol       = "tcp"
  from_port         = 3306
  to_port           = 3306
  description       = "Allow MySQL access from the o11y whitelist IP"
}

resource "aws_vpc_security_group_egress_rule" "rds" {
  count = var.enable_rds ? 1 : 0

  security_group_id = aws_security_group.rds[0].id
  cidr_ipv4         = "0.0.0.0/0"
  ip_protocol       = "-1"
  description       = "Allow all outbound traffic"
}

resource "aws_db_instance" "this" {
  count = var.enable_rds ? 1 : 0

  identifier     = local.cluster_name
  engine         = "mysql"
  engine_version = "8.4"
  instance_class = var.rds_instance_class

  allocated_storage     = 20
  max_allocated_storage = 1000
  storage_type          = "gp3"
  storage_encrypted     = true

  db_name  = "kubestore"
  username = "admin"
  password = random_password.rds[0].result

  db_subnet_group_name   = aws_db_subnet_group.this[0].name
  vpc_security_group_ids = [aws_security_group.rds[0].id]
  multi_az               = true
  publicly_accessible    = false

  backup_retention_period         = 7
  backup_window                   = "03:00-04:00"
  enabled_cloudwatch_logs_exports = ["error", "slowquery"]
  auto_minor_version_upgrade      = false
  copy_tags_to_snapshot           = true

  deletion_protection       = var.rds_deletion_protection
  skip_final_snapshot       = false
  final_snapshot_identifier = "${local.cluster_name}-final"

  tags = merge(local.common_tags, {
    Name = local.cluster_name
  })
}

# =============================================================================
# RDS credentials in Secrets Manager
# =============================================================================

resource "aws_secretsmanager_secret" "rds_credentials" {
  count = var.enable_rds ? 1 : 0

  name                    = "${local.cluster_name}-rds-credentials"
  description             = "RDS credentials for kubestore"
  recovery_window_in_days = 0

  tags = merge(local.common_tags, {
    Environment = var.env
    Region      = var.aws_region
    ClusterName = local.cluster_name
  })
}

resource "aws_secretsmanager_secret_version" "rds_credentials" {
  count = var.enable_rds ? 1 : 0

  secret_id = aws_secretsmanager_secret.rds_credentials[0].id
  secret_string = jsonencode({
    host     = aws_db_instance.this[0].address
    port     = aws_db_instance.this[0].port
    username = aws_db_instance.this[0].username
    password = random_password.rds[0].result
    dbname   = aws_db_instance.this[0].db_name
  })
}
