import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
import { paragraphRefactorService } from '@/lib/ai/services/paragraph-refactor.service'

export async function POST(request: NextRequest) {
  try {
    const session = await auth()

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

    const { text, option } = await request.json()

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

    // Map option to refactor mode
    const modeMap: Record<string, 'clarify' | 'shorten' | 'improveStyle'> = {
      'clarify': 'clarify',
      'shorten': 'shorten',
      'improve': 'improveStyle'
    }

    const mode = modeMap[option]
    if (!mode) {
      return NextResponse.json(
        { error: 'Invalid option. Use: clarify, shorten, or improve' },
        { status: 400 }
      )
    }

    // Validate word count
    const validation = paragraphRefactorService.validateWordCount(text)
    if (!validation.valid) {
      return NextResponse.json({ error: validation.error }, { status: 400 })
    }

    // Use the ParagraphRefactorService
    const result = await paragraphRefactorService.refactor(text, mode)

    return NextResponse.json({
      originalText: result.original,
      reformulatedText: result.refactored,
      option: option,
      language: result.language,
      wordCountChange: result.wordCountChange
    })
  } catch (error: any) {
    return NextResponse.json(
      { error: error.message || 'Failed to reformulate text' },
      { status: 500 }
    )
  }
}
