import type { MetadataRoute } from 'next';
import { prisma } from '@/lib/prisma';
import { locales } from '@/i18n/config';

const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000';

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const staticPaths = ['', '/about', '/services', '/products', '/projects', '/blog', '/faq', '/contact', '/devis'];

  const [services, products, posts, projects] = await Promise.all([
    prisma.service.findMany({ where: { published: true }, select: { slug: true, updatedAt: true } }),
    prisma.product.findMany({ where: { published: true }, select: { slug: true, updatedAt: true } }),
    prisma.post.findMany({ where: { published: true }, select: { slug: true, updatedAt: true } }),
    prisma.project.findMany({ where: { published: true }, select: { slug: true } })
  ]).catch(() => [[], [], [], []]);

  const entries: MetadataRoute.Sitemap = [];

  for (const locale of locales) {
    for (const path of staticPaths) {
      entries.push({ url: `${SITE_URL}/${locale}${path}`, lastModified: new Date() });
    }
    for (const s of services) {
      entries.push({ url: `${SITE_URL}/${locale}/services/${s.slug}`, lastModified: s.updatedAt });
    }
    for (const p of products) {
      entries.push({ url: `${SITE_URL}/${locale}/products/${p.slug}`, lastModified: p.updatedAt });
    }
    for (const post of posts) {
      entries.push({ url: `${SITE_URL}/${locale}/blog/${post.slug}`, lastModified: post.updatedAt });
    }
    for (const proj of projects) {
      entries.push({ url: `${SITE_URL}/${locale}/projects/${proj.slug}`, lastModified: new Date() });
    }
  }

  return entries;
}
