/**
 * 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 { readFileSync, existsSync } from 'fs';
import { join, isAbsolute } from 'path';
import { extractSecuritySchemes, getDefaultAuth } from '@/lib/api-docs/parsers/openapi/extractors/auth';
const STARTER_PATH = process.env.STARTER_PATH || 'devdoc-docs';
const LOCAL_SPEC_PATH = process.env.LOCAL_SPEC_PATH || `${STARTER_PATH}/api-reference/openapi.json`;
// Helper to resolve paths
function resolvePath(...paths) {
    if (isAbsolute(STARTER_PATH)) {
        return join(STARTER_PATH, ...paths);
    }
    return join(process.cwd(), STARTER_PATH, ...paths);
}
// Load OpenAPI spec from local file
function loadLocalSpec() {
    try {
        const relativePath = LOCAL_SPEC_PATH;
        const fullPath = relativePath.startsWith(STARTER_PATH) || isAbsolute(relativePath) ? isAbsolute(relativePath) ? relativePath : resolvePath(relativePath.replace(STARTER_PATH + '/', '')) : resolvePath(relativePath);
        if (!existsSync(fullPath)) {
            return null;
        }
        const content = readFileSync(fullPath, 'utf-8');
        return JSON.parse(content);
    } catch (error) {
        console.error('[Auth Schemes] Error loading local spec:', error);
        return null;
    }
}
export async function GET() {
    try {
        const spec = loadLocalSpec();
        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
        });
    }
}
