import { env } from "../../config/env.js";
import { one, pool, query } from "../../core/db/db.js";
import { notFound, type Ctx } from "../../core/http/route.js";
import { startSession } from "./identity.service.js";

const on = (c: Ctx) => env.DEMO_LOGIN === "on" && env.NODE_ENV !== "production" && ["localhost", "127.0.0.1", "::1", "[::1]"].includes(c.req.hostname);
/** Only accounts made by `npm run demo:users` can be opened this way, never a real person's account. */
const DEMO = "u.email LIKE '%@demo.pbps.invalid' AND u.status='active'";
export async function demoAccounts(c: Ctx) {
  if (!on(c)) return [];
  return query(pool, `SELECT u.id, u.name, r.label AS role, p.name AS provider, (SELECT GROUP_CONCAT(COALESCE(st.display_name, k.name) SEPARATOR ', ') FROM membership_scopes s LEFT JOIN training_sites st ON s.scope_type='site' AND st.id=s.scope_id LEFT JOIN training_classes k ON s.scope_type='class' AND k.id=s.scope_id WHERE s.membership_id=m.id) AS scope
    FROM users u JOIN memberships m ON m.user_id=u.id AND m.status='active' JOIN roles r ON r.id=m.role_id LEFT JOIN providers p ON p.id=m.provider_id WHERE ${DEMO} ORDER BY m.provider_id IS NOT NULL, u.id`);
}
export async function demoLogin(c: Ctx, userId: string) {
  const u = on(c) ? await one(pool, `SELECT u.id FROM users u WHERE u.id=? AND ${DEMO}`, [userId]) : undefined;
  if (!u) notFound("Demo account");
  await startSession(c, userId, false);
  return { status: "ok" };
}
