{% set config = merged_configs.get('aws_db_instance', {}) %}
{% set comments = compliance_comments.get('aws_db_instance', []) %}
# ------------------------------------------------------------------------------
# RDS Database Instance
# ------------------------------------------------------------------------------
{% for comment in comments %}
# {{ comment }}
{% endfor %}

resource "aws_db_instance" "this" {
  identifier = "{{ project_id }}-db"

  engine            = "{{ config.get('engine', 'postgres') }}"
  engine_version    = "{{ config.get('engine_version', '16') }}"
  instance_class    = "{{ config.get('instance_class', 'db.t3.micro') }}"
  allocated_storage = {{ config.get('allocated_storage', 20) }}

  db_name  = "{{ config.get('db_name', 'appdb') }}"
  username = "{{ config.get('username', 'dbadmin') }}"
  password = var.db_password

  # Encryption at rest
  storage_encrypted = {{ config.get('storage_encrypted', true) | lower }}
  kms_key_id        = {{ config.get('kms_key_id', 'null') }}

  # Network
  publicly_accessible    = {{ config.get('publicly_accessible', false) | lower }}
  db_subnet_group_name   = {{ config.get('db_subnet_group_name', 'null') }}
  vpc_security_group_ids = {{ config.get('vpc_security_group_ids', '[]') }}

  # Backup & recovery
  backup_retention_period = {{ config.get('backup_retention_period', 7) }}
  backup_window           = "{{ config.get('backup_window', '03:00-04:00') }}"

  # Monitoring
  monitoring_interval          = {{ config.get('monitoring_interval', 60) }}
  monitoring_role_arn          = {{ config.get('monitoring_role_arn', 'null') }}
  performance_insights_enabled = {{ config.get('performance_insights_enabled', true) | lower }}
  enabled_cloudwatch_logs_exports = {{ config.get('enabled_cloudwatch_logs_exports', '["postgresql", "upgrade"]') }}

  # Maintenance
  auto_minor_version_upgrade = {{ config.get('auto_minor_version_upgrade', true) | lower }}
  maintenance_window         = "{{ config.get('maintenance_window', 'sun:04:00-sun:05:00') }}"

  # Deletion protection
  deletion_protection = {{ config.get('deletion_protection', true) | lower }}
  skip_final_snapshot = {{ config.get('skip_final_snapshot', false) | lower }}

  # Multi-AZ for high availability
  multi_az = {{ config.get('multi_az', false) | lower }}

  # IAM authentication
  iam_database_authentication_enabled = {{ config.get('iam_database_authentication_enabled', true) | lower }}

  # Copy tags to snapshots
  copy_tags_to_snapshot = {{ config.get('copy_tags_to_snapshot', true) | lower }}

  tags = {
    Name      = "{{ project_id }}-db"
    ManagedBy = "complyform"
  }
}

variable "db_password" {
  description = "Database master password"
  type        = string
  sensitive   = true
}
