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

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

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

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

resource "google_compute_firewall" "ssh_firewall" {
  name        = "${var.project_name}-ssh"
  network     = google_compute_network.vpc.name
  direction   = "INGRESS"
  priority    = 1000
  target_tags = ["ssh"]
  source_ranges = [var.ssh_source_ranges]

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

resource "google_compute_firewall" "frontend_firewall" {
  name        = "${var.project_name}-frontend-http-https"
  network     = google_compute_network.vpc.name
  direction   = "INGRESS"
  priority    = 1000
  target_tags = ["frontend"]
  source_ranges = ["0.0.0.0/0"]

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

resource "google_compute_firewall" "backend_firewall" {
  name        = "${var.project_name}-frontend-to-backend-8000"
  network     = google_compute_network.vpc.name
  direction   = "INGRESS"
  priority    = 1000
  target_tags = ["backend"]
  source_tags = ["frontend"]

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

resource "google_compute_firewall" "database_firewall" {
  name        = "${var.project_name}-backend-to-database-3306"
  network     = google_compute_network.vpc.name
  direction   = "INGRESS"
  priority    = 1000
  target_tags = ["database"]
  source_tags = ["backend"]

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