import { NextRequest, NextResponse } from 'next/server'
import { sessionRepo } from '@/lib/database/repositories/session.repo'
import { messageRepo } from '@/lib/database/repositories/message.repo'

export async function GET(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params

  const session = sessionRepo.findById(id)
  if (!session) {
    return NextResponse.json({ error: 'Session not found' }, { status: 404 })
  }

  const messages = messageRepo.listBySession(id)

  const exportMessages = messages.map((m) => {
    const role = m.role
    if (role === 'assistant') {
      // Assistant messages store content as JSON array of blocks
      let blocks: unknown[] = []
      try { blocks = JSON.parse(m.content) } catch { /* plain text fallback */ }
      return { id: m.id, role, blocks, created_at: m.createdAt }
    }
    // User messages store content as plain text
    return { id: m.id, role, text: m.content, created_at: m.createdAt }
  })

  return NextResponse.json({
    exportedAt: new Date().toISOString(),
    version: '1.0',
    session: { id: session.id, title: session.title, workspace: session.workspace, model: session.model, created_at: session.createdAt },
    messages: exportMessages,
  })
}
