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

resource "google_compute_subnetwork" "frontend" {
  name          = "${var.project_name}-frontend-subnet"
  project       = var.project_name
  region        = var.region
  network       = google_compute_network.vpc.id
  ip_cidr_range = var.frontend_cidr
}

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

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

resource "google_compute_firewall" "frontend_http_https" {
  name        = "${var.project_name}-fw-frontend-http-https"
  project     = var.project_name
  network     = google_compute_network.vpc.name
  description = "Autorise HTTP/HTTPS vers les instances frontend"
  direction   = "INGRESS"

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

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

resource "google_compute_firewall" "ssh_all" {
  name        = "${var.project_name}-fw-ssh-all"
  project     = var.project_name
  network     = google_compute_network.vpc.name
  description = "Autorise SSH vers toutes les instances du VPC"
  direction   = "INGRESS"

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

  source_ranges = [var.ssh_source_ranges]
}

resource "google_compute_firewall" "frontend_to_backend_8000" {
  name        = "${var.project_name}-fw-frontend-backend-8000"
  project     = var.project_name
  network     = google_compute_network.vpc.name
  description = "Autorise le trafic TCP 8000 des instances frontend vers backend"
  direction   = "INGRESS"

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

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

resource "google_compute_firewall" "backend_to_database_3306" {
  name        = "${var.project_name}-fw-backend-database-3306"
  project     = var.project_name
  network     = google_compute_network.vpc.name
  description = "Autorise le trafic TCP 3306 des instances backend vers database"
  direction   = "INGRESS"

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

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