// scripts/generate-sitemap.ts
const fs = require('fs');
const path = require('path');
const http = require('http');
require('dotenv').config();

const API_PATH = '/api/sitemapBuilder';
const DEST_PATH = path.join(process.cwd(), 'public', 'sitemap.xml');

function fetchSitemap(): Promise<string> {
  return new Promise((resolve, reject) => {
    http
      .get(
        `${process.env.VERCEL_PROJECT_PRODUCTION_URL}${API_PATH}`,
        (res: any) => {
          let data = '';

          res.on('data', (chunk: any) => (data += chunk));
          res.on('end', () => resolve(data));
        },
      )
      .on('error', reject);
  });
}

(async () => {
  try {
    const xml = await fetchSitemap();

    fs.writeFileSync(DEST_PATH, xml, 'utf8');
    console.log('✅ Sitemap generated at public/sitemap.xml');
  } catch (err) {
    console.error('❌ Failed to generate sitemap:', err);
    process.exit(1);
  }
})();
