All files / web/src/app/api/flowcharts/suggest route.ts

0% Statements 0/44
0% Branches 0/1
0% Functions 0/1
0% Lines 0/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45                                                                                         
import { NextResponse } from 'next/server'
import {
  searchSimilarFlowcharts,
  type FlowchartSearchResult,
} from '@/lib/flowcharts/embedding-search'
import { withAuth } from '@/lib/auth/withAuth'

/**
 * POST /api/flowcharts/suggest
 *
 * Search for existing flowcharts similar to a user's topic description.
 * Used in the CreateFlowchartModal to suggest existing flowcharts before
 * generating a new one, and on the browse page for search.
 *
 * Request body: { query: string, limit?: number }
 * Response: { suggestions: FlowchartSearchResult[] }
 */
export const POST = withAuth(async (request) => {
  try {
    const body = await request.json()
    const { query, limit } = body

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

    if (query.trim().length < 3) {
      return NextResponse.json({ suggestions: [] })
    }

    // Default to 3 for create modal, allow up to 20 for browse page
    const resultLimit = typeof limit === 'number' ? Math.min(Math.max(1, limit), 20) : 3

    const suggestions = await searchSimilarFlowcharts(query, {
      limit: resultLimit,
      minSimilarity: 0.3,
    })

    return NextResponse.json({ suggestions })
  } catch (error) {
    console.error('Failed to search flowcharts:', error)
    return NextResponse.json({ error: 'Failed to search flowcharts' }, { status: 500 })
  }
})