Skip to content
import { initDb, query } from "./db.ts";
import type { ClassId } from "./heroes.ts";
import type { SessionUser } from "../utils.ts";

export interface AccountHero {
  name: string;
  class: ClassId;
  level: number;
  anima: number;
  deckSize: number;
}

export interface Account extends SessionUser {
  createdAt: string;
  hero: AccountHero | null;
}

function deckSize(value: unknown): number {
  if (typeof value !== "string") return 0;
  try {
    const parsed = JSON.parse(value);
    return Array.isArray(parsed) ? parsed.length : 0;
  } catch {
    return 0;
  }
}

export async function listAccounts(): Promise<Account[]> {
  await initDb();
  const result = await query(
    `SELECT u.id, u.email, u.name, u.role, u.created_at,
            h.name AS hero_name, h.class AS hero_class,
            h.level AS hero_level, h.anima AS hero_anima, h.deck AS hero_deck
     FROM users u LEFT JOIN heroes h ON h.user_id = u.id
     ORDER BY u.created_at ASC, u.id ASC`,
  );
  return result.rows.map((row) => ({
    id: Number(row.id),
    email: String(row.email),
    name: row.name === null ? null : String(row.name),
    role: String(row.role) as SessionUser["role"],
    createdAt: String(row.created_at),
    hero: row.hero_name === null ? null : {
      name: String(row.hero_name),
      class: String(row.hero_class) as ClassId,
      level: Number(row.hero_level),
      anima: Number(row.hero_anima),
      deckSize: deckSize(row.hero_deck),
    },
  }));
}