import db from '../db/index.js'; export function getProfile(userId) { const row = db .prepare( `SELECT u.id, u.email, u.username, u.email_verified, p.display_name, p.avatar_path, p.bio, p.chips_balance, p.updated_at FROM users u LEFT JOIN profiles p ON p.user_id = u.id WHERE u.id = ?`, ) .get(userId); if (!row) return null; return { id: row.id, email: row.email, username: row.username, emailVerified: !!row.email_verified, displayName: row.display_name, avatarPath: row.avatar_path, bio: row.bio, chips: row.chips_balance ?? 2000, updatedAt: row.updated_at, }; } export function updateProfile(userId, { displayName, bio }) { const fields = []; const values = []; if (displayName !== undefined) { fields.push('display_name = ?'); values.push(String(displayName).slice(0, 60)); } if (bio !== undefined) { fields.push('bio = ?'); values.push(String(bio).slice(0, 500)); } if (!fields.length) return getProfile(userId); fields.push("updated_at = datetime('now')"); values.push(userId); db.prepare(`UPDATE profiles SET ${fields.join(', ')} WHERE user_id = ?`).run(...values); return getProfile(userId); } export function setAvatarPath(userId, avatarPath) { db.prepare( `UPDATE profiles SET avatar_path = ?, updated_at = datetime('now') WHERE user_id = ?`, ).run(avatarPath, userId); return getProfile(userId); } export function getChipsBalance(userId) { const row = db.prepare('SELECT chips_balance FROM profiles WHERE user_id = ?').get(userId); return row?.chips_balance ?? 2000; } export function adjustChipsBalance(userId, delta) { const current = getChipsBalance(userId); const next = Math.max(0, current + delta); db.prepare( `UPDATE profiles SET chips_balance = ?, updated_at = datetime('now') WHERE user_id = ?`, ).run(next, userId); return next; } export function resetChipsBalance(userId) { const current = getChipsBalance(userId); if (current >= 100) { const err = new Error('Financial reset is only available when your chip balance is below $100.'); err.status = 403; throw err; } const RESET_AMOUNT = 2000; db.prepare( `UPDATE profiles SET chips_balance = ?, updated_at = datetime('now') WHERE user_id = ?`, ).run(RESET_AMOUNT, userId); return RESET_AMOUNT; }