import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/auth'
import { prisma } from '@/lib/prisma'

/**
 * POST /api/ai/echo/dismiss
 * Dismiss a connection for a specific note
 * Body: { noteId, connectedNoteId }
 */
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 { noteId, connectedNoteId } = body

    if (!noteId || !connectedNoteId) {
      return NextResponse.json(
        { error: 'noteId and connectedNoteId are required' },
        { status: 400 }
      )
    }

    // Find and mark matching insights as dismissed
    // We need to find insights where (note1Id = noteId AND note2Id = connectedNoteId) OR (note1Id = connectedNoteId AND note2Id = noteId)
    await prisma.memoryEchoInsight.updateMany({
      where: {
        userId: session.user.id,
        OR: [
          {
            note1Id: noteId,
            note2Id: connectedNoteId
          },
          {
            note1Id: connectedNoteId,
            note2Id: noteId
          }
        ]
      },
      data: {
        dismissed: true
      }
    })

    return NextResponse.json({ success: true })

  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to dismiss connection' },
      { status: 500 }
    )
  }
}
