// Grant or revoke the "Admin" role for a user by phone number (US +1 assumed).
// Usage: bun run scripts/make-admin.ts <phone> [--revoke]
import "dotenv/config";
import SuperTokens from "supertokens-node";
import Session from "supertokens-node/recipe/session";
import Passwordless from "supertokens-node/recipe/passwordless";
import UserRoles from "supertokens-node/recipe/userroles";

SuperTokens.init({
  framework: "custom",
  supertokens: {
    connectionURI: process.env.SUPERTOKENS_URI || "http://localhost:3567",
    apiKey: process.env.SUPERTOKENS_API_KEY || undefined,
  },
  appInfo: {
    appName: "FLXN",
    apiDomain: "http://localhost:3000",
    websiteDomain: "http://localhost:3000",
    apiBasePath: "/api/auth",
    websiteBasePath: "/auth",
  },
  recipeList: [
    Passwordless.init({ contactMethod: "PHONE", flowType: "USER_INPUT_CODE" }),
    Session.init(),
    UserRoles.init(),
  ],
});

const raw = process.argv[2];
const revoke = process.argv.includes("--revoke");
if (!raw) {
  console.error("Usage: bun run scripts/make-admin.ts <phone> [--revoke]");
  process.exit(1);
}

const digits = raw.replace(/[^\d]/g, "");
const candidates = Array.from(
  new Set([
    raw.startsWith("+") ? raw : null,
    digits.length === 10 ? `+1${digits}` : null,
    `+${digits}`,
    digits,
  ].filter(Boolean) as string[])
);

let user: { id: string } | undefined;
let matched = "";
for (const phoneNumber of candidates) {
  const users = await SuperTokens.listUsersByAccountInfo("public", { phoneNumber });
  if (users.length) {
    user = users[0];
    matched = phoneNumber;
    break;
  }
}

if (!user) {
  console.error(`No SuperTokens user found for phone (tried: ${candidates.join(", ")}).`);
  console.error("The user must have logged in at least once so their account exists.");
  process.exit(1);
}

await UserRoles.createNewRoleOrAddPermissions("Admin", []);

if (revoke) {
  const res = await UserRoles.removeUserRole("public", user.id, "Admin");
  console.log(`Removed Admin from ${matched} (user ${user.id}):`, res.status);
} else {
  const res = await UserRoles.addRoleToUser("public", user.id, "Admin");
  console.log(
    `Granted Admin to ${matched} (user ${user.id}):`,
    res.status === "OK"
      ? res.didUserAlreadyHaveRole
        ? "already had it"
        : "added"
      : res.status
  );
}

console.log("Note: sign out and back in (or refresh the session) for the role to take effect.");
process.exit(0);
