# Nova CI VPC — short-lived VPC for L1 module lifecycle testing.
#
# Created by the modules-lifecycle pipeline before testing VPC-dependent
# modules (alb, ecs-service, rds, uptime). Destroyed after all tests complete.
# Separate from the long-lived platform VPC (terraform/platform).
#
# State: spike/ci-vpc/terraform.tfstate (separate from platform/ and module states)

terraform {
  required_version = ">= 1.9, < 1.10"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
  backend "s3" {
    bucket = "nova-tfstate-581513795199-us-east-1"
    key    = "spike/ci-vpc/terraform.tfstate"
    region = "us-east-1"
  }
}

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

data "aws_availability_zones" "available" {
  state = "available"
}

resource "aws_vpc" "ci" {
  cidr_block = "10.1.0.0/16"
  tags = {
    Name               = "nova-ci-vpc"
    "nova:owner"       = "acdl"
    "nova:environment" = "ci"
  }
}

resource "aws_subnet" "ci" {
  count             = 2
  vpc_id            = aws_vpc.ci.id
  cidr_block        = cidrsubnet(aws_vpc.ci.cidr_block, 8, count.index + 1)
  availability_zone = data.aws_availability_zones.available.names[count.index]
  tags = {
    Name               = "nova-ci-subnet-${count.index}"
    "nova:owner"       = "acdl"
    "nova:environment" = "ci"
  }
}

resource "aws_internet_gateway" "ci" {
  vpc_id = aws_vpc.ci.id
  tags = {
    Name = "nova-ci-igw"
  }
}

resource "aws_route_table" "ci" {
  vpc_id = aws_vpc.ci.id
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.ci.id
  }
}

resource "aws_route_table_association" "ci" {
  count          = 2
  subnet_id      = aws_subnet.ci[count.index].id
  route_table_id = aws_route_table.ci.id
}

resource "aws_security_group" "ecs" {
  name        = "nova-ci-ecs-sg"
  description = "Security group for CI ECS services"
  vpc_id      = aws_vpc.ci.id

  ingress {
    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"]
  }
}

resource "aws_ecs_cluster" "ci" {
  name = "nova-ci-cluster"
}

output "vpc_id" {
  value = aws_vpc.ci.id
}

output "subnet_ids" {
  value = join(",", aws_subnet.ci[*].id)
}

output "ecs_security_group_id" {
  value = aws_security_group.ecs.id
}

output "cluster_arn" {
  value = aws_ecs_cluster.ci.arn
}