import xmlbuilder from 'xmlbuilder';

import * as CommonApi from "../pages/api/common";
import axios from 'axios';
import { baseUrl } from '../constants/urls';



export async function productSitemapXml() {
  const baseUrl1 = 'https://indispare.com';
 
  // const products:any = CommonApi.getRequest(`${baseUrl}/api/generate-sitemap??type=products`).then((res)=>{
  //   console.log(res,"res")
  //   return res?.data?.data;
  // }); // Replace with your product URLs

  try {
    const products:any = await CommonApi.getRequest(`${baseUrl}/api/generate-sitemap?type=products`).then((res)=>{
      // console.log(res?.data?.data?.length,"length")
    return res?.data?.data;
  });

    const root = xmlbuilder.create('urlset', { version: '1.0', encoding: 'UTF-8' })
      .att('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');

      products?.slice(0, 1000).forEach((product: any) => {
      root.ele('url')
        .ele('loc', `${product}`).up()
        .ele('lastmod', new Date().toISOString()).up()
        .ele('changefreq', 'monthly').up()
        .ele('priority', '0.7').up();
    });

    return root.end({ pretty: true });
  } catch (error) {
    console.error("Error:", error);
    throw error;
  }
}