# RDS PostgreSQL Database
resource "aws_db_subnet_group" "filamenteka" {
  name       = "${var.app_name}-db-subnet-group"
  subnet_ids = aws_subnet.public[*].id

  tags = {
    Name = "${var.app_name}-db-subnet-group"
  }
}

resource "aws_security_group" "rds" {
  name        = "${var.app_name}-rds-sg"
  description = "Security group for RDS database"
  vpc_id      = aws_vpc.main.id


  # Allow access from your local IP for development
  # IMPORTANT: Replace with your actual IP address
  ingress {
    from_port   = 5432
    to_port     = 5432
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"] # WARNING: This allows access from anywhere. Replace with your IP!
    description = "Development access - RESTRICT THIS IN PRODUCTION"
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "${var.app_name}-rds-sg"
  }
}

resource "aws_db_instance" "filamenteka" {
  identifier     = var.app_name
  engine         = "postgres"
  engine_version = "15"
  instance_class = "db.t3.micro"
  
  allocated_storage     = 20
  max_allocated_storage = 100
  storage_type          = "gp3"
  storage_encrypted     = true
  
  db_name  = "filamenteka"
  username = "filamenteka_admin"
  password = random_password.db_password.result
  
  # Make it publicly accessible for development
  publicly_accessible = true
  
  vpc_security_group_ids = [aws_security_group.rds.id]
  db_subnet_group_name   = aws_db_subnet_group.filamenteka.name
  
  backup_retention_period = 7
  backup_window          = "03:00-04:00"
  maintenance_window     = "sun:04:00-sun:05:00"
  
  deletion_protection = false  # Set to true in production
  skip_final_snapshot = true   # Set to false in production
  
  enabled_cloudwatch_logs_exports = ["postgresql"]
  
  tags = {
    Name = "${var.app_name}-db"
  }
}

resource "random_password" "db_password" {
  length  = 32
  special = false # RDS doesn't allow certain special characters
}

resource "aws_secretsmanager_secret" "db_credentials" {
  name = "${var.app_name}-db-credentials"
}

resource "aws_secretsmanager_secret_version" "db_credentials" {
  secret_id = aws_secretsmanager_secret.db_credentials.id
  secret_string = jsonencode({
    username = aws_db_instance.filamenteka.username
    password = random_password.db_password.result
    host     = aws_db_instance.filamenteka.endpoint
    port     = aws_db_instance.filamenteka.port
    database = aws_db_instance.filamenteka.db_name
  })
}

# Random password for JWT
resource "random_password" "jwt_secret" {
  length  = 64
  special = false
}