{% set config = merged_configs.get('google_sql_database_instance', {}) %}
# Compliance: {{ compliance_comments.get('google_sql_database_instance', []) | join(', ') }}
resource "google_sql_database_instance" "main" {
  name                = "{{ config.get('name', '${var.project_id}-sql') }}"
  project             = var.project_id
  region              = var.region
  database_version    = "{{ config.get('database_version', 'POSTGRES_15') }}"
  deletion_protection = {{ config.get('deletion_protection', true) | lower }}

  settings {
    tier              = "{{ config.get('tier', 'db-custom-2-8192') }}"
    availability_type = "{{ config.get('availability_type', 'REGIONAL') }}"
    disk_autoresize   = {{ config.get('disk_autoresize', true) | lower }}
    disk_size         = {{ config.get('disk_size', 20) }}
    disk_type         = "{{ config.get('disk_type', 'PD_SSD') }}"

    ip_configuration {
      ipv4_enabled    = {{ config.get('ipv4_enabled', false) | lower }}
      ssl_mode        = "{{ config.get('ssl_mode', 'ENCRYPTED_ONLY') }}"
      require_ssl     = {{ config.get('require_ssl', true) | lower }}
      private_network = {{ config.get('private_network', 'null') }}
    }

    backup_configuration {
      enabled                        = {{ config.get('backup_enabled', true) | lower }}
      binary_log_enabled             = {{ config.get('binary_log_enabled', false) | lower }}
      point_in_time_recovery_enabled = {{ config.get('point_in_time_recovery_enabled', true) | lower }}
      transaction_log_retention_days = {{ config.get('transaction_log_retention_days', 7) }}

      backup_retention_settings {
        retained_backups = {{ config.get('retained_backups', 30) }}
      }
    }

    database_flags {
      name  = "log_checkpoints"
      value = "on"
    }

    database_flags {
      name  = "log_connections"
      value = "on"
    }

    maintenance_window {
      day          = {{ config.get('maintenance_day', 7) }}
      hour         = {{ config.get('maintenance_hour', 3) }}
      update_track = "{{ config.get('update_track', 'stable') }}"
    }
  }
}
