# VPC
# resource "google_compute_network" "vpc" {
#   name                    = "mon-vpc"
#   auto_create_subnetworks = false
# }

resource "google_compute_network" "vpc_terraform" {
  name                    = "vpc-terraform-2"
  auto_create_subnetworks = false
}

# Sous-réseau
# resource "google_compute_subnetwork" "subnet" {
#   name          = "mon-subnet"
#   network       = google_compute_network.vpc.id
#   ip_cidr_range = "10.0.1.0/24"
#   region        = "europe-west1"
# }

resource "google_compute_subnetwork" "subnet_frontend" {
  name          = "frontend-2"
  network       = google_compute_network.vpc_terraform.id
  ip_cidr_range = var.frontend_cidr
  region        = var.region
}

resource "google_compute_subnetwork" "subnet_backend" {
  name          = "backend-2"
  network       = google_compute_network.vpc_terraform.id
  ip_cidr_range = var.backend_cidr
  region        = var.region
}

resource "google_compute_subnetwork" "subnet_database" {
  name          = "database-2"
  network       = google_compute_network.vpc_terraform.id
  ip_cidr_range = var.database_cidr
  region        = var.region
}

# Règles de Pare-feu
# resource "google_compute_firewall" "allow_http" {
#   name    = "allow-http"
#   network = google_compute_network.vpc.id

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

#   source_ranges = ["0.0.0.0/0"]
#   target_tags   = ["web"]
# }

resource "google_compute_firewall" "allow_user_frontend" {
  name    = "allow-user-frontend-2"
  network = google_compute_network.vpc_terraform.id

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

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

resource "google_compute_firewall" "allow_frontend_backend" {
  name    = "allow-frontend-backend-2"
  network = google_compute_network.vpc_terraform.id

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

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

resource "google_compute_firewall" "allow_ssh_all" {
  name    = "allow-ssh-all-2"
  network = google_compute_network.vpc_terraform.id

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

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

resource "google_compute_firewall" "allow_backend_database" {
  name    = "allow-backend-database-2"
  network = google_compute_network.vpc_terraform.id

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

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