/**
 * Auth Schemes API Route
 * 
 * Returns the security schemes defined in the OpenAPI spec
 * so the frontend can suggest the correct auth type
 */

import { NextResponse } from 'next/server'
import { extractSecuritySchemes, getDefaultAuth } from '@/lib/api-docs/parsers/openapi/extractors/auth'
import type { OpenAPI } from 'openapi-types'

// Import the same fetch logic as the openapi-spec route
import { CacheUtils } from '@/lib/cache'

const BRAINFISH_API_BASE_URL = process.env.BRAINFISH_API_BASE_URL || 'https://api.brainfish.ai/api'
const BRAINFISH_CATALOG_ID = process.env.BRAINFISH_CATALOG_ID || 'your_catalog_id_here'
const BRAINFISH_JWT_TOKEN = process.env.BRAINFISH_JWT_TOKEN || 'your_jwt_token_here'
const CACHE_KEY = `openapi-spec-${BRAINFISH_CATALOG_ID}`

// Fetch the OpenAPI spec directly (same as openapi-spec route)
async function fetchOpenApiSpec(): Promise<OpenAPI.Document | null> {
  try {
    // First try cache
    const cachedSpec = await CacheUtils.get<OpenAPI.Document>(CACHE_KEY)
    if (cachedSpec) {
      return cachedSpec
    }

    // Fetch from API
    const url = `${BRAINFISH_API_BASE_URL}/catalogs.openapi-spec`
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${BRAINFISH_JWT_TOKEN}`,
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ catalogId: BRAINFISH_CATALOG_ID }),
      cache: 'no-store',
    })
    
    if (!response.ok) {
      return null
    }
    
    return await response.json()
  } catch {
    return null
  }
}

export async function GET() {
  try {
    const spec = await fetchOpenApiSpec()
    
    if (!spec) {
      return NextResponse.json({
        schemes: [],
        defaultAuth: null,
      })
    }

    const schemes = extractSecuritySchemes(spec)
    const defaultAuth = getDefaultAuth(spec)

    return NextResponse.json({
      schemes,
      defaultAuth,
    })
  } catch (error) {
    return NextResponse.json({
      schemes: [],
      defaultAuth: null,
      error: error instanceof Error ? error.message : 'Unknown error',
    }, { status: 500 })
  }
}
