import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
import { getChatProvider } from '@/lib/ai/factory'
import { getSystemConfig } from '@/lib/config'
import prisma from '@/lib/prisma'

/**
 * POST /api/ai/echo/fusion
 * Generate intelligent fusion of multiple notes
 */
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 { noteIds, prompt } = body

    if (!noteIds || !Array.isArray(noteIds) || noteIds.length < 2) {
      return NextResponse.json(
        { error: 'At least 2 note IDs are required' },
        { status: 400 }
      )
    }

    // Fetch the notes
    const notes = await prisma.note.findMany({
      where: {
        id: { in: noteIds },
        userId: session.user.id
      },
      select: {
        id: true,
        title: true,
        content: true,
        createdAt: true
      }
    })

    if (notes.length !== noteIds.length) {
      return NextResponse.json(
        { error: 'Some notes not found or access denied' },
        { status: 404 }
      )
    }

    // Get AI provider
    const config = await getSystemConfig()
    const provider = getChatProvider(config)

    // Build fusion prompt
    const notesDescriptions = notes.map((note, index) => {
      return `Note ${index + 1}: "${note.title || 'Untitled'}"
${note.content}`
    }).join('\n\n')

    const fusionPrompt = `You are an expert at synthesizing and merging information from multiple sources.

TASK: Create a unified, well-structured note by intelligently combining the following notes.

${prompt ? `ADDITIONAL INSTRUCTIONS: ${prompt}\n` : ''}

NOTES TO MERGE:
${notesDescriptions}

REQUIREMENTS:
1. Create a clear, descriptive title that captures the essence of all notes
2. Merge and consolidate related information
3. Remove duplicates while preserving unique details from each note
4. Organize the content logically (use headers, bullet points, etc.)
5. Maintain the important details and context from all notes
6. Keep the tone and style consistent
7. Use markdown formatting for better readability

Output format:
# [Fused Title]

[Merged and organized content...]

Begin:`

    try {
      const fusedContent = await provider.generateText(fusionPrompt)

      return NextResponse.json({
        fusedNote: fusedContent,
        notesCount: notes.length
      })
    } catch (error) {
      return NextResponse.json(
        { error: 'Failed to generate fusion' },
        { status: 500 }
      )
    }

  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to process fusion request' },
      { status: 500 }
    )
  }
}
