locals {
  # Load the YAML files
  dataset_config = yamldecode(file("${path.module}/datasets.yml"))
  source_mapping = yamldecode(file("${path.module}/source_mapping.yml"))

  # Access the datasets map
  datasets = local.dataset_config.datasets

  # Define the layers we care about
  layers = {
    dws     = local.datasets.dws
    anls    = local.datasets.anls
    dwh     = local.datasets.dwh
    stg     = local.datasets.stg
  }

  same_layer_auth_layers = {
    dws     = local.datasets.dws
    anls    = local.datasets.anls
    dwh     = local.datasets.dwh
  }

  # 1. Same layer authorizations
  # For each layer, every dataset authorizes every other dataset in the same layer.
  same_layer_auths = flatten([
    for layer_name, ds_list in local.same_layer_auth_layers : [
      for source in ds_list : [
        for authorized in ds_list : {
          source_project     = source.project
          source_dataset     = source.dataset
          authorized_project = authorized.project
          authorized_dataset = authorized.dataset
        }
        if "${source.project}.${source.dataset}" != "${authorized.project}.${authorized.dataset}"
      ]
    ]
  ])

  # 2. Cross layer authorizations
  # dws > anls > dwh > stg > sources
  # Upper layer (authorized) > Lower layer (source)
  cross_layer_pairs = [
    { authorized_layer = "dws", source_layer = "anls" },
    { authorized_layer = "dws", source_layer = "dwh" },
    { authorized_layer = "anls", source_layer = "dwh" },
    { authorized_layer = "dwh", source_layer = "stg" },
  ]

  cross_layer_auths = flatten([
    for pair in local.cross_layer_pairs : [
      for source in local.layers[pair.source_layer] : [
        for authorized in local.layers[pair.authorized_layer] : {
          source_project     = source.project
          source_dataset     = source.dataset
          authorized_project = authorized.project
          authorized_dataset = authorized.dataset
        }
      ]
    ]
  ])

  # 3. Source to Staging authorizations
  source_stg_auths = [
    for mapping in local.source_mapping.datasets : {
      source_project     = mapping.source_project
      source_dataset     = mapping.source_dataset
      authorized_project = mapping.staging_project
      authorized_dataset = mapping.staging_dataset
    }
  ]

  # Combine all authorizations
  all_auths = concat(local.same_layer_auths, local.cross_layer_auths, local.source_stg_auths)
}

resource "google_bigquery_dataset_access" "dataset_authorization" {
  for_each = {
    for auth in local.all_auths :
    "${auth.source_project}.${auth.source_dataset}_authorizes_${auth.authorized_project}.${auth.authorized_dataset}" => auth
  }

  project    = each.value.source_project
  dataset_id = each.value.source_dataset

  dataset {
    dataset {
      project_id = each.value.authorized_project
      dataset_id = each.value.authorized_dataset
    }
    target_types = ["VIEWS"]
  }
}
