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

export async function POST(request: NextRequest) {
  try {
    const config = await getSystemConfig()
    const provider = getTagsProvider(config)

    const testContent = "This is a test note about artificial intelligence and machine learning. It contains keywords like AI, ML, neural networks, and deep learning."

    const startTime = Date.now()
    const tags = await provider.generateTags(testContent)
    const endTime = Date.now()

    if (!tags || tags.length === 0) {
      return NextResponse.json(
        {
          success: false,
          error: 'No tags generated',
          provider: config.AI_PROVIDER_TAGS || 'ollama',
          model: config.AI_MODEL_TAGS || 'granite4:latest'
        },
        { status: 500 }
      )
    }

    return NextResponse.json({
      success: true,
      provider: config.AI_PROVIDER_TAGS || 'ollama',
      model: config.AI_MODEL_TAGS || 'granite4:latest',
      tags: tags,
      responseTime: endTime - startTime
    })
  } catch (error: any) {
    const config = await getSystemConfig()

    return NextResponse.json(
      {
        success: false,
        error: error.message || 'Unknown error',
        provider: config.AI_PROVIDER_TAGS || 'ollama',
        model: config.AI_MODEL_TAGS || 'granite4:latest',
        stack: process.env.NODE_ENV === 'development' ? error.stack : undefined
      },
      { status: 500 }
    )
  }
}
