# Terraform configuration to create an Application Load Balancer (ALB) with a target group.

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 Security Group for ALB ---
resource "aws_security_group" "alb_sg" {
  name        = "MyTerraformAlbSG"
  description = "Allow HTTP traffic for ALB"
  vpc_id      = data.aws_vpc.default.id

  ingress {
    description = "HTTP from anywhere"
    from_port   = 80
    to_port     = 80
    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"]
  }

  tags = {
    Name = "MyTerraformAlbSG"
  }
}

# --- 3. Create ALB ---
resource "aws_lb" "main" {
  name               = "my-terraform-alb"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.alb_sg.id]
  subnets            = tolist(data.aws_subnets.default.ids)[0:2] # Use first two default subnets

  enable_deletion_protection = false # For demo purposes

  tags = {
    Name = "MyTerraformALB"
  }
}

# --- 4. Create Target Group ---
resource "aws_lb_target_group" "main" {
  name     = "my-terraform-alb-tg"
  port     = 80
  protocol = "HTTP"
  vpc_id   = data.aws_vpc.default.id

  health_check {
    path                = "/"
    protocol            = "HTTP"
    matcher             = "200"
    interval            = 30
    timeout             = 5
    healthy_threshold   = 2
    unhealthy_threshold = 2
  }

  tags = {
    Name = "MyTerraformALBTG"
  }
}

# --- 5. Create Listener ---
resource "aws_lb_listener" "http" {
  load_balancer_arn = aws_lb.main.arn
  port              = 80
  protocol          = "HTTP"

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.main.arn
  }
}

# --- Outputs ---
output "alb_dns_name" {
  value       = aws_lb.main.dns_name
  description = "The DNS name of the Application Load Balancer."
}

output "alb_arn" {
  value       = aws_lb.main.arn
  description = "The ARN of the Application Load Balancer."
}

output "target_group_arn" {
  value       = aws_lb_target_group.main.arn
  description = "The ARN of the Target Group."
}
