locals {
  default_branch_enabled = var.default_branch == "" ? [] : ["enabled"]
}

resource "github_repository" "this" {
  name               = var.name
  description        = var.description
  homepage_url       = var.homepage_url
  visibility         = var.visibility
  has_issues         = var.has_issues
  has_projects       = var.has_projects
  has_wiki           = var.has_wiki
  has_downloads      = var.has_downloads
  allow_merge_commit = var.allow_merge_commit
  allow_squash_merge = var.allow_squash_merge
  allow_rebase_merge = var.allow_rebase_merge
  auto_init          = var.auto_init
  gitignore_template = var.gitignore_template
  license_template   = var.license_template
  #default_branch         = var.default_branch
  topics                 = var.topics
  archived               = var.archived
  delete_branch_on_merge = var.delete_branch_on_merge
  is_template            = var.is_template

  #lifecycle {
  #  ignore_changes = [branches]
  #}
}

resource "github_branch_default" "this" {
  count      = length(local.default_branch_enabled)
  repository = github_repository.this.name
  branch     = var.default_branch
}

resource "github_team_repository" "this" {
  for_each = var.team_permissions

  team_id    = each.value["team_id"]
  repository = github_repository.this.name
  permission = each.value["permission"]
}

resource "github_repository_collaborator" "this" {
  for_each = var.user_permissions

  repository = github_repository.this.name
  username   = each.value["username"]
  permission = each.value["permission"]
}

resource "github_team_repository" "this_v2" {
  for_each = transpose(var.team_permissions_v2)

  team_id    = each.key
  repository = github_repository.this.name
  permission = length(each.value) == 1 ? each.value[0] : "non-existant-permission-to-force-error"
}

resource "github_repository_collaborator" "this_v2" {
  for_each = transpose(var.user_permissions_v2)

  repository = github_repository.this.name
  username   = each.key
  permission = length(each.value) == 1 ? each.value[0] : "non-existant-permission-to-force-error"
}
