import { initializeDatabase, pool } from "./db.js";
import { hashPassword, normalizeName, validPassword } from "./security.js";

const name = process.argv[2]?.trim() ?? "";
const password = process.env.NEW_PASSWORD ?? "";
if (!name || !validPassword(password)) {
  throw new Error("用法：NEW_PASSWORD='至少8位的新密码' npm run password:reset --workspace @cents/api -- '姓名'");
}

await initializeDatabase();
const passwordHash = await hashPassword(password);
const client = await pool.connect();
try {
  await client.query("BEGIN");
  const result = await client.query<{ id: string }>(
    "UPDATE users SET password_hash = $1, updated_at = now() WHERE name_key = $2 RETURNING id",
    [passwordHash, normalizeName(name)],
  );
  const user = result.rows[0];
  if (!user) throw new Error("未找到该用户");
  await client.query("UPDATE sessions SET revoked_at = now() WHERE user_id = $1 AND revoked_at IS NULL", [user.id]);
  await client.query("COMMIT");
  process.stdout.write("密码已重置，旧登录会话已撤销。\n");
} catch (error) {
  await client.query("ROLLBACK");
  throw error;
} finally {
  client.release();
  await pool.end();
}
