import { error } from '@sveltejs/kit';

// Import all markdown files at build time
const docs = import.meta.glob('$lib/taDocs/*.md', { 
    as: 'raw',
    eager: true 
});

export async function GET({ params }) {
    const { slug } = params;
    
    // Validate filename to prevent directory traversal attacks
    if (!slug || slug.includes('..') || slug.includes('/') || !slug.endsWith('.md')) {
        throw error(400, 'Invalid documentation file requested');
    }
    
    // Create the import path that matches our glob pattern
    const importPath = `/src/lib/taDocs/${slug}`;
    
    // Find the matching document
    const content = docs[importPath];
    
    if (!content) {
        console.error(`Documentation file not found: ${slug}`);
        // List available files for debugging
        console.error('Available files:', Object.keys(docs));
        throw error(404, 'Documentation file not found');
    }
    
    return new Response(content, {
        headers: {
            'Content-Type': 'text/markdown; charset=utf-8',
            'Cache-Control': 'max-age=600', // Cache for 10 minutes
            'Access-Control-Allow-Origin': '*' // Add CORS if needed
        }
    });
}