import { NextResponse } from 'next/server'
import { sessionRepo } from '@/lib/database/repositories/session.repo'
import { messageRepo } from '@/lib/database/repositories/message.repo'
import crypto from 'crypto'
import { isAuthError, requireUser, requireWorkspaceWriteAccess } from '@/lib/auth/session'

/**
 * POST /api/sessions/:id/compact — Compact session by replacing all messages
 * with a single summary message containing the conversation overview.
 */
export async function POST(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  let user
  try { user = await requireUser() } catch (err) { if (isAuthError(err)) return err; throw err }
  const { id } = await params

  const session = sessionRepo.findByIdAndUser(id, user.id)
  if (!session) {
    return NextResponse.json({ error: 'Session not found' }, { status: 404 })
  }
  if (session.workspace) {
    try { await requireWorkspaceWriteAccess(session.workspace) } catch (err) { if (isAuthError(err)) return err; throw err }
  }

  const messages = messageRepo.listRoleContentBySession(id)

  if (messages.length === 0) {
    return NextResponse.json({ ok: true, compacted: 0 })
  }

  // Build a compact summary of the conversation
  const turns = messages.length
  let userMsgCount = 0
  let assistantMsgCount = 0
  const topics: string[] = []

  for (const msg of messages) {
    if (msg.role === 'user') {
      userMsgCount++
      // Extract first line of user messages as topic hints
      const firstLine = msg.content.slice(0, 100).split('\n')[0].trim()
      if (firstLine && topics.length < 5) {
        topics.push(firstLine)
      }
    } else {
      assistantMsgCount++
    }
  }

  const summary = [
    `[Conversation compacted: ${turns} messages (${userMsgCount} user, ${assistantMsgCount} assistant)]`,
    '',
    topics.length > 0 ? `Topics discussed:\n${topics.map(t => `- ${t}`).join('\n')}` : '',
    '',
    'Previous context has been compacted to save memory. You may continue the conversation.',
  ].filter(Boolean).join('\n')

  const summaryContent = JSON.stringify([{ type: 'text', text: summary }])

  // Replace all messages with the summary
  messageRepo.deleteBySession(id)
  messageRepo.create({
    id: crypto.randomUUID(),
    sessionId: id,
    role: 'assistant',
    content: summaryContent,
  })

  return NextResponse.json({ ok: true, compacted: turns })
}
