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

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

    const testMessage = 'Réponds en exactement 3 mots : quel est ton nom ?'

    const startTime = Date.now()
    const response = await provider.generateText(testMessage)
    const endTime = Date.now()

    if (!response || response.trim().length === 0) {
      return NextResponse.json(
        {
          success: false,
          error: 'No response from chat provider',
          model: config.AI_MODEL_CHAT || 'granite4:latest',
        },
        { status: 500 }
      )
    }

    return NextResponse.json({
      success: true,
      model: config.AI_MODEL_CHAT || 'granite4:latest',
      chatResponse: response.trim(),
      responseTime: endTime - startTime,
    })
  } catch (error: any) {
    const config = await getSystemConfig()

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