import { NextResponse } from 'next/server'

export async function POST(request: Request) {
    try {
        const { endpoint, token, model } = await request.json()

        if (!endpoint || !token) {
            return NextResponse.json(
                { success: false, error: 'Faltan credenciales (Endpoint o Token)' },
                { status: 400 }
            )
        }

        // Prepare target URL
        let targetUrl = endpoint
        if (!targetUrl.endsWith('/messages') && !targetUrl.endsWith('/chat/completions')) {
            targetUrl = targetUrl.endsWith('/') ? `${targetUrl}v1/messages` : `${targetUrl}/v1/messages`
        }

        const start = Date.now()

        // Payload for Anthropic /v1/messages
        const body = {
            model: model || "gpt-3.5-turbo", // Fallback if no model selected
            messages: [{ role: "user", content: "Ping" }],
            max_tokens: 10
        }

        const response = await fetch(targetUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'x-api-key': token,
                'anthropic-version': '2023-06-01',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(body)
        })

        const duration = Date.now() - start

        if (!response.ok) {
            const text = await response.text()
            return NextResponse.json(
                { success: false, error: `Error ${response.status}: ${text.slice(0, 100)}` },
                { status: response.status }
            )
        }

        return NextResponse.json({ success: true, latency: duration })

    } catch (error: any) {
        console.error('AI Test Error:', error)
        return NextResponse.json(
            { success: false, error: error.message || 'Error de conexión' },
            { status: 500 }
        )
    }
}
