# Terraform configuration to create an Amazon Redshift cluster.

provider "aws" {
  region = "us-east-1"
}

# --- 1. Data Source for Default VPC and Subnets ---
data "aws_vpc" "default" {
  default = true
}

data "aws_subnets" "default" {
  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.default.id]
  }
  filter {
    name   = "default_for_az"
    values = ["true"]
  }
}

# --- 2. Create Cluster Subnet Group ---
resource "aws_redshift_subnet_group" "main" {
  name        = "my-terraform-redshift-subnet-group"
  description = "Redshift subnet group for Terraform cluster"
  subnet_ids  = tolist(data.aws_subnets.default.ids)[0:2] # Use first two default subnets

  tags = {
    Name = "MyTerraformRedshiftSubnetGroup"
  }
}

# --- 3. Create Security Group for Redshift ---
resource "aws_security_group" "redshift_sg" {
  name        = "MyTerraformRedshiftSG"
  description = "Allow Redshift traffic"
  vpc_id      = data.aws_vpc.default.id

  ingress {
    description = "Redshift from anywhere"
    from_port   = 5439
    to_port     = 5439
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"] # For simplicity, restrict in production
  }

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

  tags = {
    Name = "MyTerraformRedshiftSG"
  }
}

# --- 4. Create Redshift Cluster ---
resource "aws_redshift_cluster" "main" {
  cluster_identifier      = "my-terraform-redshift-cluster"
  node_type               = "dc2.large"
  cluster_type            = "single-node" # For demo purposes
  database_name           = "dev"
  master_username         = "admin"
  master_password         = "MySecurePassword123!" # !!! IMPORTANT: Use a strong password in production !!!
  cluster_subnet_group_name = aws_redshift_subnet_group.main.name
  vpc_security_group_ids  = [aws_security_group.redshift_sg.id]
  publicly_accessible     = true # For demo purposes
  skip_final_snapshot     = true # For demo purposes

  tags = {
    Name = "MyTerraformRedshiftCluster"
  }
}

# --- Outputs ---
output "redshift_cluster_endpoint" {
  value       = aws_redshift_cluster.main.endpoint
  description = "The endpoint address of the Redshift cluster."
}

output "redshift_cluster_id" {
  value       = aws_redshift_cluster.main.id
  description = "The ID of the Redshift cluster."
}
