import { NextResponse } from 'next/server'; import { eq, inArray } from '@/lib/db'; import { db, collections, collectionItems, watchlists, watchlistItems, alerts, savedSearches, priceTargets, notifications, loginEvents, apiKeys } from '@/lib/db'; import { getCurrentUser } from '@/lib/auth/session'; export const dynamic = 'force-dynamic'; /** Full personal data export (GDPR-style): everything the member created, as JSON. */ export async function GET() { const u = await getCurrentUser(); if (!u) return NextResponse.json({ error: 'unauthorized' }, { status: 401 }); const cols = await db().select().from(collections).where(eq(collections.userId, u.id)); const items = cols.length ? await db().select().from(collectionItems).where(inArray(collectionItems.collectionId, cols.map((c) => c.id))) : []; const wls = await db().select().from(watchlists).where(eq(watchlists.userId, u.id)); const wItems = wls.length ? await db().select().from(watchlistItems).where(inArray(watchlistItems.watchlistId, wls.map((w) => w.id))) : []; const [al, ss, pt, nt, le, keys] = await Promise.all([ db().select().from(alerts).where(eq(alerts.userId, u.id)), db().select().from(savedSearches).where(eq(savedSearches.userId, u.id)), db().select().from(priceTargets).where(eq(priceTargets.userId, u.id)), db().select().from(notifications).where(eq(notifications.userId, u.id)), db().select().from(loginEvents).where(eq(loginEvents.userId, u.id)), db().select({ id: apiKeys.id, name: apiKeys.name, prefix: apiKeys.prefix, tier: apiKeys.tier, createdAt: apiKeys.createdAt, revokedAt: apiKeys.revokedAt }).from(apiKeys).where(eq(apiKeys.userId, u.id)), ]); const { passwordHash: _p, totpSecretEnc: _t, ...profile } = u; void _p; void _t; const body = { exportedAt: new Date().toISOString(), profile, collections: cols, collectionItems: items, watchlists: wls, watchlistItems: wItems, alerts: al, savedSearches: ss, priceTargets: pt, notifications: nt, loginEvents: le, apiKeys: keys }; return new NextResponse(JSON.stringify(body, null, 2), { headers: { 'content-type': 'application/json', 'content-disposition': `attachment; filename="rareindex-export-${new Date().toISOString().slice(0, 10)}.json"` } }); }