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

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

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

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

# Firewall rules ------------------

resource "google_compute_firewall" "frontend_http" {
  name    = "${var.project_name}-frontend-http"
  network = google_compute_network.vpc.self_link

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

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

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

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

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

resource "google_compute_firewall" "frontend_backend" {
  name    = "${var.project_name}-frontend-to-backend"
  network = google_compute_network.vpc.self_link

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

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

resource "google_compute_firewall" "backend_database" {
  name    = "${var.project_name}-backend-to-database"
  network = google_compute_network.vpc.self_link

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

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