import { Elysia } from 'elysia'; import type { Holding, TaskStatus, WatchlistItem } from '@/lib/types'; import { ensureAuthSchema } from '@/lib/auth'; import { requireAuthenticatedSession } from '@/lib/server/auth-session'; import { asErrorMessage, jsonError } from '@/lib/server/http'; import { buildPortfolioSummary, recalculateHolding } from '@/lib/server/portfolio'; import { getStoreSnapshot, withStore } from '@/lib/server/store'; import { enqueueTask, getTaskById, listRecentTasks } from '@/lib/server/tasks'; const ALLOWED_STATUSES: TaskStatus[] = ['queued', 'running', 'completed', 'failed']; function nowIso() { return new Date().toISOString(); } function asRecord(value: unknown): Record { if (!value || typeof value !== 'object' || Array.isArray(value)) { return {}; } return value as Record; } function asPositiveNumber(value: unknown) { const parsed = typeof value === 'number' ? value : Number(value); return Number.isFinite(parsed) && parsed > 0 ? parsed : null; } async function handleAuthRequest(request: Request) { const auth = await ensureAuthSchema(); return auth.handler(request); } export const app = new Elysia({ prefix: '/api' }) .get('/auth', ({ request }) => handleAuthRequest(request)) .post('/auth', ({ request }) => handleAuthRequest(request)) .patch('/auth', ({ request }) => handleAuthRequest(request)) .put('/auth', ({ request }) => handleAuthRequest(request)) .delete('/auth', ({ request }) => handleAuthRequest(request)) .get('/auth/*', ({ request }) => handleAuthRequest(request)) .post('/auth/*', ({ request }) => handleAuthRequest(request)) .patch('/auth/*', ({ request }) => handleAuthRequest(request)) .put('/auth/*', ({ request }) => handleAuthRequest(request)) .delete('/auth/*', ({ request }) => handleAuthRequest(request)) .options('/auth', ({ request }) => handleAuthRequest(request)) .options('/auth/*', ({ request }) => handleAuthRequest(request)) .get('/health', async () => { const snapshot = await getStoreSnapshot(); const queue = snapshot.tasks.reduce>((acc, task) => { acc[task.status] = (acc[task.status] ?? 0) + 1; return acc; }, {}); return Response.json({ status: 'ok', version: '3.0.0', timestamp: new Date().toISOString(), queue }); }) .get('/me', async () => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } return Response.json({ user: { id: session.user.id, email: session.user.email, name: session.user.name, image: session.user.image } }); }) .get('/watchlist', async () => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } const snapshot = await getStoreSnapshot(); const items = snapshot.watchlist .filter((item) => item.user_id === session.user.id) .slice() .sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at)); return Response.json({ items }); }) .post('/watchlist', async ({ body }) => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } const payload = asRecord(body); const ticker = typeof payload.ticker === 'string' ? payload.ticker.trim().toUpperCase() : ''; const companyName = typeof payload.companyName === 'string' ? payload.companyName.trim() : ''; const sector = typeof payload.sector === 'string' ? payload.sector.trim() : ''; if (!ticker) { return jsonError('ticker is required'); } if (!companyName) { return jsonError('companyName is required'); } try { let item: WatchlistItem | null = null; await withStore((store) => { const existingIndex = store.watchlist.findIndex((entry) => { return entry.user_id === session.user.id && entry.ticker === ticker; }); if (existingIndex >= 0) { const existing = store.watchlist[existingIndex]; const updated: WatchlistItem = { ...existing, company_name: companyName, sector: sector || null }; store.watchlist[existingIndex] = updated; item = updated; return; } store.counters.watchlist += 1; const created: WatchlistItem = { id: store.counters.watchlist, user_id: session.user.id, ticker, company_name: companyName, sector: sector || null, created_at: nowIso() }; store.watchlist.unshift(created); item = created; }); return Response.json({ item }); } catch (error) { return jsonError(asErrorMessage(error, 'Failed to create watchlist item')); } }) .delete('/watchlist/:id', async ({ params }) => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } const numericId = Number(params.id); if (!Number.isInteger(numericId) || numericId <= 0) { return jsonError('Invalid watchlist id', 400); } let removed = false; await withStore((store) => { const next = store.watchlist.filter((item) => !(item.id === numericId && item.user_id === session.user.id)); removed = next.length !== store.watchlist.length; store.watchlist = next; }); if (!removed) { return jsonError('Watchlist item not found', 404); } return Response.json({ success: true }); }) .get('/portfolio/holdings', async () => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } const snapshot = await getStoreSnapshot(); const holdings = snapshot.holdings .filter((holding) => holding.user_id === session.user.id) .slice() .sort((a, b) => Number(b.market_value) - Number(a.market_value)); return Response.json({ holdings }); }) .post('/portfolio/holdings', async ({ body }) => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } const payload = asRecord(body); const ticker = typeof payload.ticker === 'string' ? payload.ticker.trim().toUpperCase() : ''; const shares = asPositiveNumber(payload.shares); const avgCost = asPositiveNumber(payload.avgCost); if (!ticker) { return jsonError('ticker is required'); } if (shares === null) { return jsonError('shares must be a positive number'); } if (avgCost === null) { return jsonError('avgCost must be a positive number'); } try { const now = nowIso(); let holding: Holding | null = null; await withStore((store) => { const existingIndex = store.holdings.findIndex((entry) => { return entry.user_id === session.user.id && entry.ticker === ticker; }); const currentPrice = asPositiveNumber(payload.currentPrice) ?? avgCost; if (existingIndex >= 0) { const existing = store.holdings[existingIndex]; const updated = recalculateHolding({ ...existing, ticker, shares: shares.toFixed(6), avg_cost: avgCost.toFixed(6), current_price: currentPrice.toFixed(6), updated_at: now, last_price_at: now }); store.holdings[existingIndex] = updated; holding = updated; return; } store.counters.holdings += 1; const created = recalculateHolding({ id: store.counters.holdings, user_id: session.user.id, ticker, shares: shares.toFixed(6), avg_cost: avgCost.toFixed(6), current_price: currentPrice.toFixed(6), market_value: '0', gain_loss: '0', gain_loss_pct: '0', last_price_at: now, created_at: now, updated_at: now }); store.holdings.unshift(created); holding = created; }); return Response.json({ holding }); } catch (error) { return jsonError(asErrorMessage(error, 'Failed to save holding')); } }) .patch('/portfolio/holdings/:id', async ({ params, body }) => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } const numericId = Number(params.id); if (!Number.isInteger(numericId) || numericId <= 0) { return jsonError('Invalid holding id'); } const payload = asRecord(body); let found = false; let updated: Holding | null = null; await withStore((store) => { const index = store.holdings.findIndex((entry) => { return entry.id === numericId && entry.user_id === session.user.id; }); if (index < 0) { return; } found = true; const existing = store.holdings[index]; const shares = asPositiveNumber(payload.shares) ?? Number(existing.shares); const avgCost = asPositiveNumber(payload.avgCost) ?? Number(existing.avg_cost); const currentPrice = asPositiveNumber(payload.currentPrice) ?? Number(existing.current_price ?? existing.avg_cost); const next = recalculateHolding({ ...existing, shares: shares.toFixed(6), avg_cost: avgCost.toFixed(6), current_price: currentPrice.toFixed(6), updated_at: nowIso(), last_price_at: nowIso() }); store.holdings[index] = next; updated = next; }); if (!found) { return jsonError('Holding not found', 404); } return Response.json({ holding: updated }); }) .delete('/portfolio/holdings/:id', async ({ params }) => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } const numericId = Number(params.id); if (!Number.isInteger(numericId) || numericId <= 0) { return jsonError('Invalid holding id'); } let removed = false; await withStore((store) => { const next = store.holdings.filter((holding) => { return !(holding.id === numericId && holding.user_id === session.user.id); }); removed = next.length !== store.holdings.length; store.holdings = next; }); if (!removed) { return jsonError('Holding not found', 404); } return Response.json({ success: true }); }) .get('/portfolio/summary', async () => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } const snapshot = await getStoreSnapshot(); const summary = buildPortfolioSummary( snapshot.holdings.filter((holding) => holding.user_id === session.user.id) ); return Response.json({ summary }); }) .post('/portfolio/refresh-prices', async () => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } try { const task = await enqueueTask({ userId: session.user.id, taskType: 'refresh_prices', payload: {}, priority: 80 }); return Response.json({ task }); } catch (error) { return jsonError(asErrorMessage(error, 'Failed to queue refresh task')); } }) .post('/portfolio/insights/generate', async () => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } try { const task = await enqueueTask({ userId: session.user.id, taskType: 'portfolio_insights', payload: {}, priority: 70 }); return Response.json({ task }); } catch (error) { return jsonError(asErrorMessage(error, 'Failed to queue insights task')); } }) .get('/portfolio/insights/latest', async () => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } const snapshot = await getStoreSnapshot(); const insight = snapshot.insights .filter((entry) => entry.user_id === session.user.id) .slice() .sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at))[0] ?? null; return Response.json({ insight }); }) .get('/filings', async ({ request }) => { const { response } = await requireAuthenticatedSession(); if (response) { return response; } const url = new URL(request.url); const tickerFilter = url.searchParams.get('ticker')?.trim().toUpperCase(); const limitValue = Number(url.searchParams.get('limit') ?? 50); const limit = Number.isFinite(limitValue) ? Math.min(Math.max(Math.trunc(limitValue), 1), 250) : 50; const snapshot = await getStoreSnapshot(); const filtered = tickerFilter ? snapshot.filings.filter((filing) => filing.ticker === tickerFilter) : snapshot.filings; const filings = filtered .slice() .sort((a, b) => Date.parse(b.filing_date) - Date.parse(a.filing_date)) .slice(0, limit); return Response.json({ filings }); }) .post('/filings/sync', async ({ body }) => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } const payload = asRecord(body); const ticker = typeof payload.ticker === 'string' ? payload.ticker.trim().toUpperCase() : ''; if (!ticker) { return jsonError('ticker is required'); } try { const limit = typeof payload.limit === 'number' ? payload.limit : Number(payload.limit); const task = await enqueueTask({ userId: session.user.id, taskType: 'sync_filings', payload: { ticker, limit: Number.isFinite(limit) ? limit : 20 }, priority: 90 }); return Response.json({ task }); } catch (error) { return jsonError(asErrorMessage(error, 'Failed to queue filings sync task')); } }) .post('/filings/:accessionNumber/analyze', async ({ params }) => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } const accessionNumber = params.accessionNumber?.trim() ?? ''; if (accessionNumber.length < 4) { return jsonError('Invalid accession number'); } try { const task = await enqueueTask({ userId: session.user.id, taskType: 'analyze_filing', payload: { accessionNumber }, priority: 65 }); return Response.json({ task }); } catch (error) { return jsonError(asErrorMessage(error, 'Failed to queue filing analysis task')); } }) .get('/tasks', async ({ request }) => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } const url = new URL(request.url); const limitValue = Number(url.searchParams.get('limit') ?? 20); const limit = Number.isFinite(limitValue) ? Math.min(Math.max(Math.trunc(limitValue), 1), 200) : 20; const rawStatuses = url.searchParams.getAll('status'); const statuses = rawStatuses.filter((status): status is TaskStatus => { return ALLOWED_STATUSES.includes(status as TaskStatus); }); const tasks = await listRecentTasks( session.user.id, limit, statuses.length > 0 ? statuses : undefined ); return Response.json({ tasks }); }) .get('/tasks/:taskId', async ({ params }) => { const { session, response } = await requireAuthenticatedSession(); if (response) { return response; } const task = await getTaskById(params.taskId, session.user.id); if (!task) { return jsonError('Task not found', 404); } return Response.json({ task }); }); export const GET = app.fetch; export const POST = app.fetch; export const PATCH = app.fetch; export const PUT = app.fetch; export const DELETE = app.fetch; export const OPTIONS = app.fetch;