/// <reference path="../pb_data/types.d.ts" />
//
// Issue #16 — Auto-provisioning & role assignment for Azure (Entra ID) users.
//
// PocketBase auto-creates a `team_members` auth record on the first OIDC login
// (name is filled from the OIDC `name` claim via the collection's mappedFields).
// These hooks add the application-specific bits:
//
//   * default `role` from an admin allow-list (env ENTRA_ADMIN_EMAILS),
//   * default `enrollment_status = "not_started"` so new users go through the
//     existing onboarding screen,
//   * re-sync the admin role on every login so allow-list changes take effect
//     without manual edits.
//
// The allow-list is a comma-separated list of e-mail addresses, e.g.:
//   ENTRA_ADMIN_EMAILS=rve@respellion.nl,admin@respellion.nl
//
// resolveRole itself lives in pb_hooks/utils.js and is pulled in per-callback
// via require() — PocketBase's JSVM runs each hook callback below as its own
// isolated program, so a shared top-level function here would not be in scope
// at call time. See pb_hooks/utils.js for details. Keep the logic in sync with
// src/lib/azureAuth.js (resolveRole / parseAdminEmails), which carries the
// canonical, unit-tested version for the frontend/tests.

// On creation (first login): set defaults before the record is persisted.
onRecordCreate(function (e) {
  const { resolveRole } = require(`${__hooks}/utils.js`);
  const email = e.record.get("email") || "";

  e.record.set("role", resolveRole(email));

  if (!e.record.get("enrollment_status")) {
    e.record.set("enrollment_status", "not_started");
  }

  // Fallback name when the IdP supplied no `name` claim.
  if (!e.record.get("name")) {
    e.record.set("name", email ? email.split("@")[0] : "Onbekend");
  }

  e.next();
}, "team_members");

// On every successful auth (incl. OIDC): guarantee the admin role for
// allow-list members. ESCALATE-ONLY (#27): the allow-list grants admin, it no
// longer demotes — otherwise every role promotion made through TeamManager
// would be reverted on the member's next login. Demotion runs through
// TeamManager; allow-list members cannot be demoted (the list wins on their
// next login).
onRecordAuthRequest(function (e) {
  const { resolveRole } = require(`${__hooks}/utils.js`);
  const email = e.record.get("email") || "";
  if (resolveRole(email) === "admin" && e.record.get("role") !== "admin") {
    e.record.set("role", "admin");
    e.app.save(e.record);
  }
  e.next();
}, "team_members");
