/**
 * Next.js Pages Router analyzer
 * Analyzes API routes in pages/api directory
 */
import * as fs from 'fs';
import * as path from 'path';
/**
 * Analyze Next.js Pages Router API routes
 */
export async function analyzeNextPages(pagesDir = 'pages/api') {
    const routes = [];
    try {
        const apiDir = path.join(process.cwd(), pagesDir);
        if (!fs.existsSync(apiDir)) {
            console.warn('pages/api directory not found');
            return routes;
        }
        // Recursively scan API directory
        const scanDir = (dir, basePath = '') => {
            const entries = fs.readdirSync(dir, { withFileTypes: true });
            for (const entry of entries) {
                const fullPath = path.join(dir, entry.name);
                if (entry.isDirectory()) {
                    // Handle dynamic routes like [id]
                    const dirName = entry.name.startsWith('[') && entry.name.endsWith(']')
                        ? `:${entry.name.slice(1, -1)}`
                        : entry.name;
                    scanDir(fullPath, `${basePath}/${dirName}`);
                }
                else if (entry.isFile() && /\.(ts|js)$/.test(entry.name)) {
                    // Convert filename to route path
                    const fileName = entry.name.replace(/\.(ts|js)$/, '');
                    let routePath = basePath;
                    if (fileName !== 'index') {
                        // Handle dynamic params like [id].ts
                        const paramName = fileName.startsWith('[') && fileName.endsWith(']')
                            ? `:${fileName.slice(1, -1)}`
                            : fileName;
                        routePath += `/${paramName}`;
                    }
                    // Read file to detect HTTP methods
                    const content = fs.readFileSync(fullPath, 'utf-8');
                    const methods = detectMethods(content);
                    // Create route for each detected method
                    methods.forEach(method => {
                        routes.push({
                            method,
                            path: `/api${routePath}`,
                            description: `${method} /api${routePath}`,
                            tags: ['api'],
                            middleware: detectMiddleware(content),
                            parameters: extractParameters(routePath),
                            responses: {
                                '200': { description: 'Successful response' }
                            }
                        });
                    });
                }
            }
        };
        scanDir(apiDir);
    }
    catch (error) {
        console.error('Error analyzing Next.js Pages routes:', error.message);
    }
    return routes;
}
/**
 * Detect HTTP methods in Next.js API route
 */
function detectMethods(content) {
    const methods = new Set();
    // Check for req.method checks
    const methodChecks = content.match(/req\.method\s*===?\s*['"`](\w+)['"`]/g) || [];
    methodChecks.forEach(check => {
        const match = check.match(/['"`](\w+)['"`]/);
        if (match)
            methods.add(match[1]);
    });
    // If no explicit methods found, assume it handles all methods
    if (methods.size === 0) {
        methods.add('GET');
        methods.add('POST');
    }
    return Array.from(methods);
}
/**
 * Detect middleware usage
 */
function detectMiddleware(content) {
    const middleware = [];
    // Check for common middleware patterns
    if (content.includes('auth') || content.includes('authenticate')) {
        middleware.push('auth');
    }
    if (content.includes('cors')) {
        middleware.push('cors');
    }
    return middleware;
}
/**
 * Extract parameters from route path
 */
function extractParameters(routePath) {
    const params = [];
    const paramMatches = routePath.match(/:(\w+)/g) || [];
    paramMatches.forEach(param => {
        const name = param.slice(1);
        params.push({
            name,
            in: 'path',
            required: true,
            type: 'string',
            description: `Path parameter: ${name}`
        });
    });
    return params;
}
