import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
import { notebookSummaryService } from '@/lib/ai/services'

/**
 * POST /api/ai/notebook-summary - Generate summary for a notebook
 */
export async function POST(request: NextRequest) {
  try {
    const session = await auth()

    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, error: 'Unauthorized' },
        { status: 401 }
      )
    }

    const body = await request.json()
    const { notebookId, language = 'en' } = body

    if (!notebookId || typeof notebookId !== 'string') {
      return NextResponse.json(
        { success: false, error: 'Missing required field: notebookId' },
        { status: 400 }
      )
    }

    // Check if notebook belongs to user
    const { prisma } = await import('@/lib/prisma')
    const notebook = await prisma.notebook.findFirst({
      where: {
        id: notebookId,
        userId: session.user.id,
      },
    })

    if (!notebook) {
      return NextResponse.json(
        { success: false, error: 'Notebook not found' },
        { status: 404 }
      )
    }

    // Generate summary
    const summary = await notebookSummaryService.generateSummary(
      notebookId,
      session.user.id,
      language
    )

    if (!summary) {
      return NextResponse.json({
        success: true,
        data: null,
        message: 'No summary available (notebook may be empty)',
      })
    }

    return NextResponse.json({
      success: true,
      data: summary,
    })
  } catch (error) {
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Failed to generate notebook summary',
      },
      { status: 500 }
    )
  }
}
