# À vous de créer :
# 1. Un VPC personnalisé avec auto_create_subnetworks = false
resource "google_compute_network" "VPC" {
    name = "vpc"
    auto_create_subnetworks = false
}

# 2. Trois sous-réseaux (frontend, backend, database)
resource "google_compute_subnetwork" "frontend" {
    name          = "${var.project_name}-frontend"
    ip_cidr_range = var.frontend_cidr
    region        = var.region
    network       = google_compute_network.vpc.id
}
resource "google_compute_subnetwork" "backend" {
    name          = "${var.project_name}-backend"
    ip_cidr_range = var.backend_cidr
    region        = var.region
    network       = google_compute_network.vpc.id
}
resource "google_compute_subnetwork" "database" {
    name          = "${var.project_name}-database"
    ip_cidr_range = var.database_cidr
    region        = var.region
    network       = google_compute_network.vpc.id
}

# 3. Règles de firewall :
# HTTP/HTTPS → frontend
resource "google_compute_firewall" "frontend_http" {
    name    = "${var.project_name}-frontend-http"
    network = google_compute_network.vpc.name

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

    target_tags = ["frontend"]
    source_ranges = ["0.0.0.0/0"]
}

# SSH → all
resource "google_compute_firewall" "ssh" {
    name    = "${var.project_name}-ssh"
    network = google_compute_network.vpc.name

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

    target_tags   = ["ssh"]
    source_ranges = ["0.0.0.0/0"]
}

# Port 8000 : frontend → backend
resource "google_compute_firewall" "frontend_backend" {
    name    = "${var.project_name}-frontend-to-backend"
    network = google_compute_network.vpc.name

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

    source_tags = ["frontend"]
    target_tags = ["backend"]
}

# Port 3306 : backend → database
resource "google_compute_firewall" "backend_database" {
    name    = "${var.project_name}-backend-to-database"
    network = google_compute_network.vpc.name

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

    source_tags = ["backend"]
    target_tags = ["database"]
}