resource "aws_security_group" "main_cache" {
  name        = "main-cache"
  description = "Allow inbound traffic for Valkey"
  vpc_id      = var.aws_vpc_id

  ingress {
    from_port   = 6379
    to_port     = 6379
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

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

resource "aws_elasticache_subnet_group" "main_cache" {
  name        = "main-cache"
  description = "Main Cache Subnet Group"
  subnet_ids  = [var.aws_subnets.a, var.aws_subnets.b]
}

resource "aws_elasticache_replication_group" "main_cache" {
  replication_group_id = var.main_cache_replication_group_id
  description          = "Main Cache Replication Group"

  node_type = "cache.t2.micro"

  engine               = "valkey"
  engine_version       = "8.2"
  parameter_group_name = "default.valkey8"

  port                       = 6379
  network_type               = "ipv4"
  auto_minor_version_upgrade = false

  security_group_ids = [aws_security_group.main_cache.id]
  subnet_group_name  = aws_elasticache_subnet_group.main_cache.name

  lifecycle {
    ignore_changes  = [num_cache_clusters]
    prevent_destroy = true
  }

  log_delivery_configuration {
    destination_type = "cloudwatch-logs"
    destination      = "/elasticache/valkey/instance/main-cache/engine"
    log_format       = "text"
    log_type         = "engine-log"
  }

  log_delivery_configuration {
    destination_type = "cloudwatch-logs"
    destination      = "/elasticache/valkey/instance/main-cache/slow"
    log_format       = "text"
    log_type         = "slow-log"
  }
}
