/**
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

locals {
  tfvars = {
    perimeters = {
      for k, v in try(module.vpc-sc.perimeters, {}) :
      k => v.id
    }
  }
}

resource "google_storage_bucket_object" "version" {
  count = (
    local.output_files.storage_bucket != null &&
    fileexists("fast_version.txt") ? 1 : 0
  )
  bucket         = local.output_files.storage_bucket
  name           = "versions/${local.defaults.stage_name}-version.txt"
  source         = "fast_version.txt"
  source_md5hash = filemd5("fast_version.txt")
}

resource "local_file" "tfvars" {
  for_each        = local.output_files.local_path == null ? {} : { 1 = 1 }
  file_permission = "0644"
  filename        = "${pathexpand(local.output_files.local_path)}/tfvars/${local.defaults.stage_name}.auto.tfvars.json"
  content         = jsonencode(local.tfvars)
}

resource "google_storage_bucket_object" "tfvars" {
  count          = local.output_files.storage_bucket != null ? 1 : 0
  bucket         = local.output_files.storage_bucket
  name           = "tfvars/${local.defaults.stage_name}.auto.tfvars.json"
  content        = jsonencode(local.tfvars)
  source_md5hash = md5(jsonencode(local.tfvars))
}

output "tfvars" {
  description = "Terraform variable files for the following stages."
  sensitive   = true
  value       = local.tfvars
}

output "vpc_sc_perimeter_default" {
  description = "Raw default perimeter resource."
  sensitive   = true
  value       = try(module.vpc-sc.perimeters["default"], null)
}
