#data "authentik_property_mapping_provider_scope" "nextcloud" {
#  name = "Nextcloud Profile"
#}
resource "authentik_property_mapping_provider_scope" "nextcloud-scope" {
  name       = "Nextcloud Profile"
  scope_name = "profile"
  expression = <<EOF
# Extract all groups the user is a member of
groups = [group.name for group in user.ak_groups.all()]

# Nextcloud admins must be members of a group called "admin".
# This is static and cannot be changed.
# We append a fictional "admin" group to the user's groups if they are an admin in authentik.
# This group would only be visible in Nextcloud and does not exist in authentik.
if user.is_superuser and "Nextcloud Admin" not in groups:
    groups.append("admin")

return {
    "name": request.user.name,
    "groups": groups,
    # To set a quota set the "nextcloud_quota" property in the user's attributes
    "quota": user.group_attributes().get("nextcloud_quota", None),
    # To connect an already existing user, set the "nextcloud_user_id" property in the
    # user's attributes to the username of the corresponding user on Nextcloud.
    "user_id": user.attributes.get("nextcloud_user_id", str(user.uuid)),
 }
EOF
}

resource "random_id" "nextcloud_client_id" {
  byte_length = 16
}

#resource "authentik_provider_oauth2" "nextcloud" {
#  name = "Nextcloud"
#  #  Required. You can use the output of:
#  #     $ openssl rand -hex 16
#  client_id = random_id.nextcloud_client_id.id
#
#  # Optional: will be generated if not provided
#  # client_secret = "my_client_secret"
#
#  sub_mode           = "user_uuid"
#  authorization_flow = data.authentik_flow.default-provider-authorization-implicit-consent.id
#  invalidation_flow = data.authentik_flow.default-invalidation-flow.id
#
#  allowed_redirect_uris = [
#    {
#      matching_mode = "strict"
#      url           = "https://cloud.lab.cowley.tech/apps/user_oidc/code",
#    }
#  ]
#
#  property_mappings = [
#    data.authentik_property_mapping_provider_scope.scope-email.id,
#    authentik_property_mapping_provider_scope.nextcloud-scope.id
#  ]
#
#  lifecycle {
#    ignore_changes = [
#      signing_key,
#      authentication_flow,
#    ]
#  }
#}
#
#resource "authentik_application" "nextcloud" {
#  name              = "Nextcloud"
#  slug              = "nextcloud"
#  protocol_provider = authentik_provider_oauth2.nextcloud.id
#}

resource "authentik_group" "nextcloud_admins" {
  name = "Nextcloud Admins"
}