import type { DatabaseSync } from 'node:sqlite';
import argon2 from 'argon2';
import { createUser, getUserByEmail, getUserById } from '../db/repos/users.ts';
import type { UserRow } from '../types/db.js';

export async function registerUser(
  db: DatabaseSync,
  email: string,
  password: string,
): Promise<UserRow | null> {
  const existing = getUserByEmail(db, email);
  if (existing) throw new Error('email already registered');
  const hash = await argon2.hash(password);
  return createUser(db, { email, passwordHash: hash });
}

export async function verifyUser(
  db: DatabaseSync,
  email: string,
  password: string,
): Promise<UserRow | null> {
  const user = getUserByEmail(db, email);
  if (!user) return null;
  const ok = await argon2.verify(user.password_hash, password);
  if (!ok) return null;
  return user;
}

export function getUser(db: DatabaseSync, id: number): UserRow | null {
  return getUserById(db, id);
}
