import { NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { auth } from '@/auth'
import { validateEmbedding } from '@/lib/utils'

/**
 * Admin endpoint to validate all embeddings in the database
 * Returns a list of notes with invalid embeddings
 */
export async function GET() {
  try {
    const session = await auth()
    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    // Check if user is admin
    const user = await prisma.user.findUnique({
      where: { id: session.user.id },
      select: { role: true }
    })

    if (!user || user.role !== 'ADMIN') {
      return NextResponse.json({ error: 'Forbidden - Admin only' }, { status: 403 })
    }

    // Fetch all notes with embeddings
    const allNotes = await prisma.note.findMany({
      select: {
        id: true,
        title: true,
        noteEmbedding: true
      }
    })

    const invalidNotes: Array<{
      id: string
      title: string
      issues: string[]
    }> = []

    let validCount = 0
    let missingCount = 0
    let invalidCount = 0

    for (const note of allNotes) {
      // Check if embedding is missing
      if (!note.noteEmbedding?.embedding) {
        missingCount++
        invalidNotes.push({
          id: note.id,
          title: note.title || 'Untitled',
          issues: ['Missing embedding']
        })
        continue
      }

      // Validate embedding
      try {
        if (!note.noteEmbedding?.embedding) continue
        const embedding = JSON.parse(note.noteEmbedding.embedding) as number[]
        const validation = validateEmbedding(embedding)

        if (!validation.valid) {
          invalidCount++
          invalidNotes.push({
            id: note.id,
            title: note.title || 'Untitled',
            issues: validation.issues
          })
        } else {
          validCount++
        }
      } catch (error) {
        invalidCount++
        invalidNotes.push({
          id: note.id,
          title: note.title || 'Untitled',
          issues: [`Failed to parse embedding: ${error}`]
        })
      }
    }

    return NextResponse.json({
      success: true,
      summary: {
        total: allNotes.length,
        valid: validCount,
        missing: missingCount,
        invalid: invalidCount
      },
      invalidNotes
    })
  } catch (error) {
    console.error('[EMBEDDING_VALIDATION] Error:', error)
    return NextResponse.json(
      { success: false, error: String(error) },
      { status: 500 }
    )
  }
}
