#------------------------------------
# RDS Cluster
#------------------------------------
resource "aws_kms_key" "customer_portal_kms" {
  description = "RDS KMS Key"
  enable_key_rotation = true
}

resource "aws_db_subnet_group" "customer_portal_rds_subnets" {
  name        = "customer_portal_rds_subnets"
  description = "Customer Portal RDS Private subnet"
  subnet_ids  = var.private_subnets
}

# yeah, I alphabatized it. Don't you alphabatized your config files? 
resource "aws_db_instance" "postgres" {
  allocated_storage           = 20
  apply_immediately           = "true"
  auto_minor_version_upgrade  = "true"
  db_subnet_group_name        = aws_db_subnet_group.customer_portal_rds_subnets.name
  backup_window               = "03:00-06:00"
  backup_retention_period     = 7
  ca_cert_identifier          = "rds-ca-2017"
  deletion_protection         = var.environment == "test" ? "false" : "true"
  delete_automated_backups    = "true"
  engine                      = "postgres"
  engine_version              = var.environment == "test" ? "12.4" : "10.15"
  final_snapshot_identifier   = "customerportal"
  instance_class              = "db.t2.small"
  identifier                  = "customerportal"
  kms_key_id                  = aws_kms_key.customer_portal_kms.arn
  maintenance_window          = "Mon:00:00-Mon:03:00"
  name                        = "customerportal"
  password                    = var.environment == "test" ? "foobarbaz" : "050ff734-fb33-9248-13e4-7d8ad2e899a0"
  port                        = 5432
  skip_final_snapshot         = var.environment == "test" ? "true" : "false"
  storage_type                = "gp2"
  storage_encrypted           = "true"
  tags                        = merge( var.standard_tags, var.tags )
  username                    = "portal"
  vpc_security_group_ids      = [ aws_security_group.postgres.id, ]
}

#------------------------------------
# Security Groups
#------------------------------------

resource "aws_security_group" "postgres" {
  name        = "customer_portal_postgres_inbound_sg"
  description = "Allow Customer Portal HTTP Traffic Inbound"
  vpc_id      = var.vpc_id
}

resource "aws_security_group_rule" "customer_portal_postgres_inbound" {
  security_group_id = aws_security_group.postgres.id

  type        = "ingress"
  from_port   = 5432
  to_port     = 5432
  protocol    = "tcp"
  cidr_blocks = ["10.0.0.0/8"]
}
