# 1. VPC personnalisé
resource "google_compute_network" "vpc_network" {
  project                 = var.project_id
  name                    = "three-tier-vpc"
  auto_create_subnetworks = false # Exigence respectée
  routing_mode            = "REGIONAL"
}

# 2. Sous-réseaux (frontend, backend, database)
resource "google_compute_subnetwork" "frontend_subnet" {
  project     = var.project_id
  name        = "frontend-subnet"
  ip_cidr_range = var.frontend_cidr
  region      = var.region
  network     = google_compute_network.vpc_network.id
}

resource "google_compute_subnetwork" "backend_subnet" {
  project     = var.project_id
  name        = "backend-subnet"
  ip_cidr_range = var.backend_cidr
  region      = var.region
  network     = google_compute_network.vpc_network.id
}

resource "google_compute_subnetwork" "database_subnet" {
  project     = var.project_id
  name        = "database-subnet"
  ip_cidr_range = var.database_cidr
  region      = var.region
  network     = google_compute_network.vpc_network.id
}

# 3. Règles de firewall (4 règles)

# Règle 1: HTTP/HTTPS vers frontend (80, 443)
resource "google_compute_firewall" "allow_web" {
  project     = var.project_id
  name        = "allow-http-https-frontend"
  network     = google_compute_network.vpc_network.name
  direction   = "INGRESS"
  source_ranges = ["0.0.0.0/0"]
  target_tags   = ["frontend"] 

  allow {
    protocol = "tcp"
    ports    = ["80", "443"]
  }
}

# Règle 2: SSH vers toutes les instances (22)
resource "google_compute_firewall" "allow_ssh" {
  project     = var.project_id
  name        = "allow-ssh-all"
  network     = google_compute_network.vpc_network.name
  direction   = "INGRESS"
  source_ranges = var.ssh_source_ranges
  target_tags   = ["ssh"] 

  allow {
    protocol = "tcp"
    ports    = ["22"]
  }
}

# Règle 3: Port 8000 de frontend vers backend
resource "google_compute_firewall" "allow_frontend_to_backend" {
  project     = var.project_id
  name        = "allow-frontend-to-backend-8000"
  network     = google_compute_network.vpc_network.name
  direction   = "INGRESS"
  source_tags   = ["frontend"]
  target_tags   = ["backend"] 

  allow {
    protocol = "tcp"
    ports    = ["8000"]
  }
}

# Règle 4: Port 3306 de backend vers database
resource "google_compute_firewall" "allow_backend_to_database" {
  project     = var.project_id
  name        = "allow-backend-to-database-3306"
  network     = google_compute_network.vpc_network.name
  direction   = "INGRESS"
  source_tags   = ["backend"]
  target_tags   = ["database"] 

  allow {
    protocol = "tcp"
    ports    = ["3306"]
  }
}