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'

const STORE = path.join(process.env.UPLOAD_DIR || path.join(process.cwd(), 'uploads'), 'trades-status.json')

// GET /api/trades/<profile>/transactions — one profile's transaction history.
//
// Split out of /api/trades so the 15s poll doesn't carry every profile's ledger to render one.
// Reads the same blob the mini pushes; nothing extra is stored and the mini is unchanged.
export async function GET(_req: Request, { params }: { params: Promise<{ profile: string }> }) {
  const session = await getAdminSession()
  if (!session) return NextResponse.json({ error: 'unauthorized' }, { status: 401 })
  const { profile } = await params
  try {
    const data = JSON.parse(fs.readFileSync(STORE, 'utf8'))
    const p = (data.profiles || []).find((x: { profile?: string }) => x?.profile === profile)
    if (!p) return NextResponse.json({ error: 'unknown profile' }, { status: 404 })
    return NextResponse.json({ profile, transactions: p.transactions || [], ingestedAt: data.ingestedAt || null })
  } catch {
    return NextResponse.json({ error: 'no data yet' }, { status: 503 })
  }
}
