/**
 * OpenAPI Spec API Route
 * 
 * Returns the OpenAPI specification from local file
 */ import { NextResponse } from 'next/server';
import { readFileSync, existsSync } from 'fs';
import { join, isAbsolute } from 'path';
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)) {
            console.warn('[OpenAPI] Spec file not found:', fullPath);
            return null;
        }
        const content = readFileSync(fullPath, 'utf-8');
        return JSON.parse(content);
    } catch (error) {
        console.error('[OpenAPI] Error loading local spec:', error);
        return null;
    }
}
export async function GET() {
    try {
        const spec = loadLocalSpec();
        if (!spec) {
            return NextResponse.json({
                openapi: '3.0.0',
                info: {
                    title: 'API Documentation',
                    version: '1.0.0',
                    description: 'OpenAPI specification not found.'
                },
                paths: {}
            }, {
                headers: {
                    'Content-Type': 'application/json',
                    'Cache-Control': 'no-cache, no-store, must-revalidate'
                }
            });
        }
        return NextResponse.json(spec, {
            headers: {
                'Content-Type': 'application/json',
                'Cache-Control': 'no-cache, no-store, must-revalidate'
            }
        });
    } catch (error) {
        console.error('[OpenAPI] Unexpected error:', error);
        return NextResponse.json({
            openapi: '3.0.0',
            info: {
                title: 'API Documentation',
                version: '1.0.0',
                description: 'Error loading specification.'
            },
            paths: {},
            error: error instanceof Error ? error.message : 'Unknown error'
        }, {
            status: 500
        });
    }
}
