'use server';

// app/(api)/sitemap/route.ts
import { NextResponse } from 'next/server';
import { productCategoriesData } from '../product_categories/data';
import { host } from '@/config';
import { projects } from '../projects/data';

const pages = [
  '/',
  '/about-us',
  '/contact-us',
  '/blog',
  '/product-categories',
  '/projects',
];

const locales = ['en', 'fa'];

export async function GET() {
  try {
    pages.push(
      ...productCategoriesData.map(
        (productCategory) => `/product-categories/${productCategory.id}`,
      ),
    );
    pages.push(...projects.map((project) => `/projects/${project.id}`));

    const urls = pages.flatMap((page) =>
      locales.map((locale) => {
        const loc = `/${locale}`;
        return `
          <url>
            <loc>${host}${loc}${page}</loc>
            <changefreq>weekly</changefreq>
            <priority>0.8</priority>
          </url>
        `;
      }),
    );

    const xml = `<?xml version="1.0" encoding="UTF-8"?>
      <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
        ${urls.join('\n')}
      </urlset>`;

    return new NextResponse(xml, {
      headers: {
        'Content-Type': 'application/xml',
      },
    });
  } catch (err) {
    console.error('Sitemap generation failed:', err);
    return new NextResponse('Internal Server Errorsssssss', { status: 500 });
  }
}
