import { NextResponse } from 'next/server'

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

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

        // Try standard /v1/models endpoint
        // If user provided "https://api.example.com/v1", we append "/models"
        let targetUrl = endpoint
        if (targetUrl.endsWith('/')) {
            targetUrl = `${targetUrl}v1/models`
        } else if (!targetUrl.endsWith('/models')) {
            targetUrl = `${targetUrl}/v1/models`
        }

        const response = await fetch(targetUrl, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`,
                'x-api-key': token
            }
        })

        if (!response.ok) {
            const text = await response.text()
            return NextResponse.json({ success: false, error: text }, { status: response.status })
        }

        const data = await response.json()
        // Normalizing response: OpenAI/Anthropic usually return { data: [{ id: 'model-name' }, ...] }

        let models: string[] = []
        if (Array.isArray(data.data)) {
            models = data.data.map((m: any) => m.id)
        } else if (Array.isArray(data)) {
            models = data.map((m: any) => m.id || m.model || m)
        }

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

    } catch (error: any) {
        return NextResponse.json({ success: false, error: error.message }, { status: 500 })
    }
}
