import type { MetadataRoute } from 'next';
import { db } from '@/lib/db';

export const dynamic = 'force-dynamic';

function publicOrigin() {
  const raw = process.env.APP_URL ?? 'http://localhost:3000';
  try {
    const url = new URL(raw);
    return url.origin;
  } catch {
    return 'http://localhost:3000';
  }
}

/** Indexable public URLs only — never offers, dashboard, admin, or private data. */
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const origin = publicOrigin();
  const entries: MetadataRoute.Sitemap = [
    { url: `${origin}/`, changeFrequency: 'weekly', priority: 1 },
  ];

  try {
    const stores = await db().business.findMany({
      where: {
        suspendedAt: null,
        products: { some: { status: 'PUBLISHED' } },
      },
      select: {
        slug: true,
        updatedAt: true,
        products: {
          where: { status: 'PUBLISHED' },
          select: { slug: true, updatedAt: true },
          take: 200,
          orderBy: { updatedAt: 'desc' },
        },
      },
      take: 5000,
      orderBy: { updatedAt: 'desc' },
    });

    for (const store of stores) {
      entries.push({
        url: `${origin}/store/${store.slug}`,
        lastModified: store.updatedAt,
        changeFrequency: 'daily',
        priority: 0.8,
      });
      for (const product of store.products) {
        entries.push({
          url: `${origin}/store/${store.slug}/p/${product.slug}`,
          lastModified: product.updatedAt,
          changeFrequency: 'weekly',
          priority: 0.6,
        });
      }
    }
  } catch {
    // Build-time / DB outage: still publish platform home.
  }

  return entries;
}
