import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
import { notebookSuggestionService } from '@/lib/ai/services/notebook-suggestion.service'

export async function POST(req: NextRequest) {
  try {
    const session = await auth()
    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const body = await req.json()
    const { noteContent, language = 'en' } = body

    if (!noteContent || typeof noteContent !== 'string') {
      return NextResponse.json({ error: 'noteContent is required' }, { status: 400 })
    }

    // Minimum content length for suggestion (20 words as per specs)
    const wordCount = noteContent.trim().split(/\s+/).length
    if (wordCount < 20) {
      return NextResponse.json({
        suggestion: null,
        reason: 'content_too_short',
        message: 'Note content too short for meaningful suggestion'
      })
    }

    // Get suggestion from AI service
    const suggestedNotebook = await notebookSuggestionService.suggestNotebook(
      noteContent,
      session.user.id,
      language
    )

    return NextResponse.json({
      suggestion: suggestedNotebook,
      confidence: suggestedNotebook ? 0.8 : 0 // Placeholder confidence score
    })
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to generate suggestion' },
      { status: 500 }
    )
  }
}
