const db = require('../db');

exports.getSitemap = async (req, res) => {
    try {
        const baseUrl = 'https://infoseclabs.io';
        
        // Static Routes
        const staticRoutes = [
            '/',
            '/login',
            '/register',
            '/news',
            '/academy',
            '/missions',
            '/apt-groups',
            '/blog',
            '/pricing',
            '/faq',
            '/help',
            '/dashboard',
            '/privacy',
            '/terms',
            '/leaderboard'
        ];

        let xml = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`;

        // Add Static Routes
        staticRoutes.forEach(route => {
            xml += `
    <url>
        <loc>${baseUrl}${route}</loc>
        <changefreq>daily</changefreq>
        <priority>${route === '/' ? '1.0' : '0.8'}</priority>
    </url>`;
        });

        // 1. Fetch Learning Paths
        try {
            const result = await db.query('SELECT id, updated_at FROM learning_paths');
            result.rows.forEach(path => {
                const updated = new Date(path.updated_at).toISOString();
                xml += `
    <url>
        <loc>${baseUrl}/academy/path/${path.id}</loc>
        <lastmod>${updated}</lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.9</priority>
    </url>`;
            });
        } catch (dbError) {
            console.error('Sitemap DB Error (Learning Paths):', dbError);
        }

        // 2. Fetch Blog Posts
        try {
            const blogResult = await db.query("SELECT slug, updated_at FROM blog_posts WHERE status = 'published'");
            blogResult.rows.forEach(post => {
                const updated = post.updated_at ? new Date(post.updated_at).toISOString() : new Date().toISOString();
                xml += `
    <url>
        <loc>${baseUrl}/blog/${post.slug}</loc>
        <lastmod>${updated}</lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.7</priority>
    </url>`;
            });
        } catch (dbError) {
            console.error('Sitemap DB Error (Blog Posts):', dbError);
        }

        // 3. Fetch Operations/Missions
        try {
            // Use is_active for operations; assuming created_at as updated if updated_at is null
            const opsResult = await db.query("SELECT id, slug, created_at FROM operations WHERE is_active = 1");
            opsResult.rows.forEach(op => {
                const slug = op.slug || op.id; // Fallback to ID if slug missing (shouldn't happen after migration)
                const updated = op.created_at ? new Date(op.created_at).toISOString() : new Date().toISOString();
                xml += `
    <url>
        <loc>${baseUrl}/missions/${slug}</loc>
        <lastmod>${updated}</lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.8</priority>
    </url>`;
            });
        } catch (dbError) {
            console.error('Sitemap DB Error (Operations):', dbError);
        }

        // 4. Fetch Public User Profiles
        try {
            // Include active users in the sitemap
            const usersResult = await db.query("SELECT username, created_at FROM users");
            if (usersResult && usersResult.rows) {
                usersResult.rows.forEach(user => {
                    const updated = user.created_at ? new Date(user.created_at).toISOString() : new Date().toISOString();
                    // Basic urlencode for the URL in case there are spaces or special characters in username
                    const encodedUsername = encodeURIComponent(user.username);
                    xml += `
    <url>
        <loc>${baseUrl}/profile/${encodedUsername}</loc>
        <lastmod>${updated}</lastmod>
        <changefreq>monthly</changefreq>
        <priority>0.6</priority>
    </url>`;
                });
            }
        } catch (dbError) {
            console.error('Sitemap DB Error (User Profiles):', dbError);
        }

        // Close XML tag
        xml += `
</urlset>`;

        res.header('Content-Type', 'text/xml');
        res.send(xml);

    } catch (error) {
        console.error('Sitemap Generation Error:', error);
        res.status(500).send('Error generating sitemap');
    }
};
