// One demo account per role, for testing only:  npm run demo:users
import bcrypt from "bcryptjs";
import { randomBytes } from "node:crypto";
import { env } from "../src/config/env.js";
import { execute, insert, one, pool, query } from "../src/core/db/db.js";

if (env.NODE_ENV === "production") throw new Error("Demo accounts are never created in production.");
const [first, second] = await query(pool, "SELECT p.id, p.code FROM providers p JOIN training_classes c ON c.provider_id=p.id AND c.is_cancelled=0 JOIN trainees t ON t.class_id=c.id WHERE p.project_id=1 GROUP BY p.id ORDER BY SUM(c.effective_end>CURRENT_DATE) DESC, COUNT(*) DESC LIMIT 2");
if (!first) throw new Error("There is no provider with classes yet.");
const site = await one(pool, "SELECT site_id AS id FROM training_classes WHERE provider_id=? AND is_cancelled=0 GROUP BY site_id ORDER BY SUM(effective_end>CURRENT_DATE) DESC, COUNT(*) DESC LIMIT 1", [first["id"]]);
const classes = await query(pool, "SELECT id FROM training_classes WHERE provider_id=? AND is_cancelled=0 ORDER BY effective_end DESC, id LIMIT 2", [first["id"]]);
async function add(role: string, key: string, name: string, providerId: string | null, scopes: [string, string][] = []): Promise<void> {
  const email = `${key}@demo.pbps.invalid`, r = (await one(pool, "SELECT id FROM roles WHERE code=?", [role]))!;
  const old = await one(pool, "SELECT id FROM users WHERE email=?", [email]);
  // The password is random and thrown away: a demo account opens only with the demo buttons.
  const uid = old ? String(old["id"]) : await insert(pool, "users", { name, email, password_hash: await bcrypt.hash(randomBytes(24).toString("hex"), 12), status: "active", two_factor_method: "none" });
  await execute(pool, "UPDATE users SET name=?, status='active' WHERE id=?", [name, uid]);
  const m = await one(pool, "SELECT id FROM memberships WHERE user_id=? AND project_id=1", [uid]);
  const mid = m ? String(m["id"]) : await insert(pool, "memberships", { project_id: 1, user_id: uid, role_id: r["id"], provider_id: providerId, status: "active" });
  await execute(pool, "UPDATE memberships SET role_id=?, provider_id=?, status='active' WHERE id=?", [r["id"], providerId, mid]);
  await execute(pool, "DELETE FROM membership_scopes WHERE membership_id=?", [mid]);
  for (const [t, id] of scopes) await insert(pool, "membership_scopes", { membership_id: mid, scope_type: t, scope_id: id });
}
const roles = await query(pool, "SELECT code, label, provider_bound FROM roles WHERE is_system=1 ORDER BY id");
for (const x of roles) {
  const code = String(x["code"]), bound = Boolean(x["provider_bound"]);
  await add(code, code, `Demo ${x["label"]}`, bound ? String(first["id"]) : null, code === "tp_site_lead" && site ? [["site", String(site["id"])]] : code === "tp_attendance_clerk" ? classes.map((k): [string, string] => ["class", String(k["id"])]) : []);
}
// A second provider shows that one provider never sees another provider's data.
if (second) await add("tp_admin", "tp_admin_2", `Demo TP admin (${second["code"]})`, String(second["id"]));
console.log(`${roles.length + (second ? 1 : 0)} demo accounts are ready. They work while DEMO_LOGIN=on.`);
await pool.end();
