import { NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
import { getAdminSession } from '@/lib/auth'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

// The mini POSTs trade status to /api/trades-ingest, which writes it here.
const STORE = path.join(process.env.UPLOAD_DIR || path.join(process.cwd(), 'uploads'), 'trades-status.json')

// GET /api/trades — serve the last status pushed by the mini.
//
// Deliberately WITHOUT each profile's `transactions`. The dashboard polls this every 15s but
// renders at most ONE profile's history at a time (the card you expanded), so shipping all 24
// ledgers cost ~110KB of every 181KB response to display none of it — and it grew with the
// ledgers. Each profile keeps `txnCount` instead, which is all the collapsed UI needs (the
// "show all N" label and the "N open" row); the records come from
// /api/trades/[profile]/transactions when a history panel is actually open.
export async function GET() {
  const session = await getAdminSession()
  if (!session) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  try {
    const data = JSON.parse(fs.readFileSync(STORE, 'utf8'))
    const profiles = (data.profiles || []).map((p: Record<string, unknown>) => {
      const { transactions, ...rest } = p as { transactions?: unknown[] }
      return { ...rest, txnCount: Array.isArray(transactions) ? transactions.length : 0 }
    })
    return NextResponse.json({ profiles, plays: data.plays || [], analytics: data.analytics || null, capital: data.capital || [], settings: data.settings || null, fund: data.fund || null, token: data.token || null, ingestedAt: data.ingestedAt || null, now: Date.now() })
  } catch {
    return NextResponse.json({ profiles: [], plays: [], analytics: null, capital: [], ingestedAt: null, now: Date.now(), error: 'no data yet' })
  }
}
