resource "random_string" "rds_password_zrok_billing" {
  length = 16
  special = true
  override_special = "!#+"
}

resource "aws_secretsmanager_secret" "engine_service_postgres_pass_zrok_billing" {
  name = "postgres_pass_billing_${local.environment}"
  description = "The password of the Postgres RDS instance that stores engine."
}

resource "aws_secretsmanager_secret_version" "engine_service_postgres_pass_zrok_billing" {
  secret_id = aws_secretsmanager_secret.engine_service_postgres_pass_zrok_billing.id
  secret_string = random_string.rds_password_zrok_billing.result
}


resource "aws_db_instance" "zrok_billing_rds_instance" {
  identifier        = "zrok-billing-db-${local.environment}"
  allocated_storage = 20
  engine            = "postgres"
  engine_version    = local.workspace["billing_postgres_version"]
  instance_class    = local.workspace["rds_size"]
  db_name           = "myzrokdb"
  username          = "billing"
  password          = random_string.rds_password_zrok_billing.result
  skip_final_snapshot = false
  auto_minor_version_upgrade = false

  // Because we're assuming a VPC, we use this option, but only one SG id
  vpc_security_group_ids = [aws_security_group.zrok_billing_db_sg.id]

  // We're creating a subnet group in the module and passing in the name
  db_subnet_group_name = aws_db_subnet_group.main_db_subnet_group_billing.name
  parameter_group_name = aws_db_parameter_group.postgres_db_zrok_billing.name

  // We want the multi-az setting to be toggleable, but off by default
  multi_az                = local.workspace["rds_multi_az"]
  storage_type            = "gp2"
  publicly_accessible     = false
  backup_retention_period = 7
//  backup_window           = "00:00-00:59"
//  maintenance_window      = "00:00-00:59"

  // Postgres requires kms_key_id for replica sets to be explicitly stated.
  //kms_key_id              = aws_kms_key.zrok.arn

  // Only apply to new instances
  storage_encrypted       = true
  lifecycle {
    prevent_destroy = true
    ignore_changes  = [storage_encrypted, tags]
  }

  // Tags
  tags = local.cost_tags
}




resource "aws_db_subnet_group" "main_db_subnet_group_billing" {
  name        = "zrok-billing-db-subnetgrp-${local.environment}"
  description = "RDS subnet group"
  subnet_ids  = data.terraform_remote_state.zrok-core.outputs.vpc_subnet_private_ids
}

resource "aws_db_parameter_group" "postgres_db_zrok_billing" {
  name   = "zrok-billing-postgres-db-${local.environment}"
  family = local.workspace["billing_postgres_family"]

  parameter {
    name         = "log_min_duration_statement"
    value        =  local.workspace["log_min_duration_statement"]
    apply_method = "immediate"
  }

  parameter {
    name         = "log_statement"
    value        = "mod"
    apply_method = "immediate"
  }
}
