import type { PoolClient } from "pg";
import { createId, hashPassword, normalizeName, validPassword } from "./security.js";

export const PERSONAL_LEDGER_NAME = "个人账本";

export async function createUserWithPersonalLedger(client: PoolClient, name: string, password: string) {
  const trimmedName = name.trim();
  if (!trimmedName || trimmedName.length > 40) throw new Error("用户名应为 1 至 40 个字符");
  if (!validPassword(password)) throw new Error("密码应为 8 至 128 个字符");

  const user = { id: createId(), name: trimmedName };
  const passwordHash = await hashPassword(password);
  await client.query(
    "INSERT INTO users (id, name, name_key, password_hash) VALUES ($1, $2, $3, $4)",
    [user.id, user.name, normalizeName(user.name), passwordHash],
  );
  const ledgerId = createId();
  await client.query(
    `INSERT INTO ledgers (id, name, color, default_currency, personal_owner_id)
     VALUES ($1, $2, '#087f72', 'CNY', $3)`,
    [ledgerId, PERSONAL_LEDGER_NAME, user.id],
  );
  await client.query(
    "INSERT INTO ledger_members (ledger_id, user_id, role) VALUES ($1, $2, 'owner')",
    [ledgerId, user.id],
  );
  return user;
}
