/// <reference path="../pb_data/types.d.ts" />
//
// Issue #22 — Allow OAuth2 sign-up on team_members.
//
// The collection was created with `createRule: null` on the assumption that
// the OAuth2 flow bypasses it. It does not: PocketBase applies the createRule
// to the automatic record creation on a first OIDC login, so every first
// login failed with 403 "Only superusers can perform this action". Since the
// pre-Azure records were intentionally dropped, EVERY user was a first login
// and nobody could sign in.
//
// `@request.context = "oauth2"` scopes record creation to the OAuth2 flow
// only — plain REST creates (e.g. anonymous POST /records, which could
// otherwise pre-seed rogue admin profiles) keep being rejected.
//
// Environments that have not applied 1781000000 yet get this rule directly
// from that (updated) migration; this follow-up exists for databases where it
// already ran with the old `null` rule (Labs). Applying it twice is harmless.
migrate((app) => {
  let col;
  try {
    col = app.findCollectionByNameOrId("team_members");
  } catch (_) {
    console.log("allow_oauth2_signup: team_members does not exist — skipping.");
    return;
  }
  if (col.type !== "auth") {
    console.log("allow_oauth2_signup: team_members is not an auth collection — skipping.");
    return;
  }
  col.createRule = '@request.context = "oauth2"';
  app.save(col);
}, (app) => {
  // Down: restore the (broken) superuser-only rule.
  let col;
  try {
    col = app.findCollectionByNameOrId("team_members");
  } catch (_) {
    return;
  }
  if (col.type !== "auth") {
    return;
  }
  col.createRule = null;
  app.save(col);
});
