terraform {
  required_version = ">= 1.5.0"
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = ">= 5.0"
    }
  }
}

provider "google" {
  project = var.project
}

locals {
  common_labels = {
    managed_by = "terragrunt"
    unit       = "ingestion-extract-bigquery"
    source     = var.source_name
  }
}

# ---------------------------------------------------------------------------
# Snapshot bucket: transient Parquet snapshots (written by `bq extract`, read by
# the gcs_bulk_load COPY INTO) plus durable manifest/log prefixes. One bucket,
# prefixed by purpose; must be co-located with the BigQuery dataset for bq extract.
# Short lifecycle on snapshots - raw Cloud Lake is the durable copy.
# ---------------------------------------------------------------------------
resource "google_storage_bucket" "data" {
  name                        = var.bucket
  project                     = var.project
  location                    = var.location
  uniform_bucket_level_access = true
  public_access_prevention    = "enforced"
  # Lets `terragrunt destroy` remove the bucket even with transient objects present.
  force_destroy = true
  labels        = local.common_labels

  lifecycle_rule {
    condition {
      age            = var.snapshot_expire_days
      matches_prefix = ["${var.snapshot_prefix}/"]
    }
    action {
      type = "Delete"
    }
  }

  lifecycle_rule {
    condition {
      age            = var.metadata_expire_days
      matches_prefix = ["${var.manifest_prefix}/", "${var.log_prefix}/"]
    }
    action {
      type = "Delete"
    }
  }

  lifecycle_rule {
    condition {
      days_since_noncurrent_time = 3
    }
    action {
      type = "Delete"
    }
  }
}

# ---------------------------------------------------------------------------
# Loader reader: the service account whose key the gcs_bulk_load COPY INTO uses to
# read the snapshot bucket - read only. Mirrors the TiDB extract's loader_reader
# IAM user. The key's base64 JSON is the load secrets.env METADB_GCS_CREDENTIAL.
# ---------------------------------------------------------------------------
resource "google_service_account" "loader_reader" {
  account_id   = "${var.source_name}-gcs-loader-reader"
  display_name = "GCS loader reader for ${var.source_name} (Cloud Lake COPY)"
  project      = var.project
}

resource "google_storage_bucket_iam_member" "loader_reader" {
  bucket = google_storage_bucket.data.name
  role   = "roles/storage.objectViewer"
  member = "serviceAccount:${google_service_account.loader_reader.email}"
}

resource "google_service_account_key" "loader_reader" {
  service_account_id = google_service_account.loader_reader.name
}
