import fs from 'fs';
import path from 'path';
import { locationData, serviceData, blogPostData } from '../src/data/seoData';

const BASE_URL = process.env.BASE_URL || 'https://bayareait.services';

const generateSitemap = () => {
    const currentDate = new Date().toISOString().split('T')[0];

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

    const staticPages = [
        '',
        '/locations',
        '/services',
        '/blog',
        '/contact',
        '/about',
        '/privacy-policy',
        '/terms-of-service'
    ];

    staticPages.forEach(page => {
        xml += `  <url>
    <loc>${BASE_URL}${page}</loc>
    <lastmod>${currentDate}</lastmod>
    <changefreq>monthly</changefreq>
    <priority>${page === '' ? '1.0' : '0.8'}</priority>
  </url>
`;
    });

    locationData.forEach(page => {
        xml += `  <url>
    <loc>${BASE_URL}/${page.slug}</loc>
    <lastmod>${currentDate}</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.9</priority>
  </url>
`;
    });

    serviceData.forEach(page => {
        xml += `  <url>
    <loc>${BASE_URL}/${page.slug}</loc>
    <lastmod>${currentDate}</lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.9</priority>
  </url>
`;
    });

    blogPostData.filter(post => !('redirect' in post) || !post.redirect).forEach(post => {
        xml += `  <url>
    <loc>${BASE_URL}/${post.slug}</loc>
    <lastmod>${currentDate}</lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.7</priority>
  </url>
`;
    });

    xml += `</urlset>`;
    return xml;
};

const sitemap = generateSitemap();
const outputPath = path.resolve(process.cwd(), 'public/sitemap.xml');
const publicDir = path.dirname(outputPath);

if (!fs.existsSync(publicDir)) {
    fs.mkdirSync(publicDir, { recursive: true });
}

fs.writeFileSync(outputPath, sitemap);
console.log(`Sitemap generated at ${outputPath}`);
