variable "environment" {
  description = "Deployment environment"
  type        = string
}

variable "project_name" {
  description = "Project name"
  type        = string
}

variable "rds_endpoint" {
  description = "RDS instance endpoint"
  type        = string
}

variable "db_password" {
  description = "Generated RDS password"
  type        = string
  sensitive   = true
}

variable "elasticache_endpoint" {
  description = "ElastiCache primary endpoint"
  type        = string
}

variable "redis_auth_token" {
  description = "ElastiCache auth token"
  type        = string
  sensitive   = true
}

variable "secrets" {
  description = "Secrets to store"
  type        = map(string)
  default     = {}
}

resource "aws_secretsmanager_secret" "main" {
  name = "${var.project_name}-${var.environment}-app-secrets"

  description = "Application secrets for ${var.project_name} (${var.environment})"

  tags = {
    Name = "${var.project_name}-${var.environment}-app-secrets"
    Environment = var.environment
  }
}

resource "aws_secretsmanager_secret_version" "main" {
  secret_id = aws_secretsmanager_secret.main.id

  secret_string = jsonencode(merge({
    DATABASE_URL = "postgresql://shieldai:${var.db_password}@${var.rds_endpoint}:5432/shieldai"
    REDIS_URL    = "redis://:${var.redis_auth_token}@${var.elasticache_endpoint}:6379"
    NODE_ENV     = var.environment
    LOG_LEVEL    = var.environment == "production" ? "info" : "debug"
  }, var.secrets))
}

output "secrets_manager_arn" {
  description = "Secrets Manager ARN"
  value       = aws_secretsmanager_secret.main.arn
}

output "secrets_manager_name" {
  description = "Secrets Manager secret name"
  value       = aws_secretsmanager_secret.main.name
}
