// Create (or report) an app user in the PocketBase "users" collection, using
// superuser credentials. App users log in to the web/phone apps via the API
// Server's /api/auth/login.
//
// Usage (PowerShell):
//   $env:PB_URL="http://10.2.1.10:8027"
//   $env:PB_ADMIN_EMAIL="admin@carcontrole.local"
//   $env:PB_ADMIN_PASSWORD="..."
//   node scripts/create-user.mjs <email> <password> [name]

const PB_URL = (process.env.PB_URL || "http://10.2.1.10:8027").replace(/\/+$/, "");
const ADMIN_EMAIL = process.env.PB_ADMIN_EMAIL;
const ADMIN_PASSWORD = process.env.PB_ADMIN_PASSWORD;
const COLLECTION = process.env.AUTH_USERS_COLLECTION || "users";

const [, , email, password, name] = process.argv;

if (!ADMIN_EMAIL || !ADMIN_PASSWORD) {
  console.error("Set PB_ADMIN_EMAIL and PB_ADMIN_PASSWORD.");
  process.exit(1);
}
if (!email || !password) {
  console.error("Usage: node scripts/create-user.mjs <email> <password> [name]");
  process.exit(1);
}
if (password.length < 8) {
  console.error("Password must be at least 8 characters (PocketBase requirement).");
  process.exit(1);
}

async function authenticate() {
  for (const ep of [
    "/api/collections/_superusers/auth-with-password",
    "/api/admins/auth-with-password",
  ]) {
    const res = await fetch(PB_URL + ep, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ identity: ADMIN_EMAIL, password: ADMIN_PASSWORD }),
    });
    if (res.ok) return (await res.json()).token;
  }
  throw new Error("Admin authentication failed.");
}

async function main() {
  const token = await authenticate();
  const res = await fetch(PB_URL + `/api/collections/${COLLECTION}/records`, {
    method: "POST",
    headers: { "Content-Type": "application/json", Authorization: token },
    body: JSON.stringify({
      email,
      password,
      passwordConfirm: password,
      name: name || email.split("@")[0],
      emailVisibility: true,
      verified: true,
    }),
  });
  const text = await res.text();
  if (!res.ok) {
    if (text.includes("validation_not_unique") || res.status === 400) {
      console.error(`Could not create user (maybe it already exists):\n${text}`);
    } else {
      console.error(`Failed: ${res.status} ${text}`);
    }
    process.exit(1);
  }
  console.log(`✓ User created: ${email}`);
  console.log("  Log in via the web app or POST /api/auth/login.");
}

main().catch((e) => {
  console.error("Error:", e.message);
  process.exit(1);
});
