# VPC
resource "google_compute_network" "vpc" {
    name                    = "${var.project_name}-vpc"
    auto_create_subnetworks = false
}

# Sous-réseaux
resource "google_compute_subnetwork" "frontend" {
    name          = "${var.project_name}-frontend"
    network       = google_compute_network.vpc.id
    ip_cidr_range = var.frontend_cidr
    region        = var.region
}

resource "google_compute_subnetwork" "backend" {
    name          = "${var.project_name}-backend"
    network       = google_compute_network.vpc.id
    ip_cidr_range = var.backend_cidr
    region        = var.region
}

resource "google_compute_subnetwork" "database" {
    name          = "${var.project_name}-database"
    network       = google_compute_network.vpc.id
    ip_cidr_range = var.database_cidr
    region        = var.region
}

# Firewall
resource "google_compute_firewall" "allow_http" {
    name    = "${var.project_name}-allow-http"
    network = google_compute_network.vpc.id

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

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

resource "google_compute_firewall" "allow_ssh" {
    name    = "${var.project_name}-allow-ssh"
    network = google_compute_network.vpc.id

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

    source_ranges = [var.ssh_source_ranges]
    target_tags   = ["ssh"]
}

resource "google_compute_firewall" "allow_frontend_to_backend" {
    name    = "${var.project_name}-allow-frontend-to-backend"
    network = google_compute_network.vpc.id

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

    source_ranges = [var.frontend_cidr]
    source_tags   = ["frontend"]
    target_tags   = ["backend"]
}

resource "google_compute_firewall" "allow_backend_to_database" {
    name    = "${var.project_name}-allow-backend-to-database"
    network = google_compute_network.vpc.id

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

    source_ranges = [var.backend_cidr]
    source_tags   = ["backend"]
    target_tags   = ["database"]
}