import { NextResponse } from 'next/server';
import { join } from 'path';
import { readFileSync, existsSync } from 'fs';
/**
 * robots.txt - Auto-generated robots file for search engines
 */ const DOCS_DIR = join(process.cwd(), 'templates', 'starter');
const BASE_URL = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000';
function loadDocsConfig() {
    const configPath = join(DOCS_DIR, 'docs.json');
    if (!existsSync(configPath)) return null;
    try {
        const content = readFileSync(configPath, 'utf-8');
        return JSON.parse(content);
    } catch  {
        return null;
    }
}
function generateRobotsTxt(config) {
    const baseUrl = config.seo?.metatags?.canonical || BASE_URL;
    const isNoIndex = config.seo?.metatags?.robots === 'noindex';
    const lines = [];
    lines.push('# robots.txt generated by Benjy');
    lines.push('');
    lines.push('User-agent: *');
    if (isNoIndex) {
        lines.push('Disallow: /');
    } else {
        lines.push('Allow: /');
        lines.push('');
        lines.push('# Disallow API routes');
        lines.push('Disallow: /api/');
    }
    lines.push('');
    lines.push(`Sitemap: ${baseUrl}/sitemap.xml`);
    lines.push('');
    return lines.join('\n');
}
export async function GET() {
    try {
        // Check for custom robots.txt first
        const customPath = join(DOCS_DIR, 'robots.txt');
        if (existsSync(customPath)) {
            const customContent = readFileSync(customPath, 'utf-8');
            return new NextResponse(customContent, {
                headers: {
                    'Content-Type': 'text/plain; charset=utf-8',
                    'Cache-Control': 'public, max-age=3600'
                }
            });
        }
        // Generate default robots.txt
        const config = loadDocsConfig();
        const content = generateRobotsTxt(config || {});
        return new NextResponse(content, {
            headers: {
                'Content-Type': 'text/plain; charset=utf-8',
                'Cache-Control': 'public, max-age=3600'
            }
        });
    } catch (error) {
        console.error('Error generating robots.txt:', error);
        return new NextResponse('Error generating robots.txt', {
            status: 500
        });
    }
}
