/**
 * XML sitemaps + robots.txt (SEO_INSTRUCTIONS Phase 6), generated from the data on request.
 *
 *   /sitemap.xml                 index of every child sitemap below
 *   /sitemap-brands-N.xml        brand pages (≤ 40,000 URLs per file) with <image:image> pack images
 *   /sitemap-bn-brands-N.xml     Bangla brand pages (only where a Bangla page exists)
 *   /sitemap-generics.xml        generic pages + their "all brands" pages
 *   /sitemap-bn-generics.xml     Bangla generic pages
 *   /sitemap-companies.xml       company pages
 *   /sitemap-taxonomy.xml        drug classes, dosage forms, indications
 *   /sitemap-vet.xml  /sitemap-agro.xml   catalogue hubs (product pages join them in Phase 12)
 *   /sitemap-pages.xml           home, A–Z lists and information pages
 *
 * Only indexable URLs are listed (same rules as the pages' robots meta). <lastmod> comes from updated_at.
 */

/** One row from a data source. `bn`: a Bangla page exists. */
export type SitemapRow = { slug: string; lastmod?: string | null; image?: string | null; bn?: boolean };

/** Where the rows come from: the database (production) or the website's sample JSON (no database yet). */
export type SitemapSource = {
  brands(): Promise<SitemapRow[]>;
  generics(): Promise<SitemapRow[]>;
  companies(): Promise<SitemapRow[]>;
  drugClasses(): Promise<SitemapRow[]>;
  dosageForms(): Promise<SitemapRow[]>;
  indications(): Promise<SitemapRow[]>;
  /** public reviewer profiles (Phase 7); placeholders like "[Pharmacist name]" are left out */
  reviewers(): Promise<SitemapRow[]>;
  /** vet / agro product pages (Phase 12), real names only */
  catalogueProducts(cat: 'vet' | 'agro'): Promise<SitemapRow[]>;
};

export const MAX_URLS = 40_000;

/** Hubs and information pages. A–Z letter pages are added per letter that has entries. */
export const STATIC_PAGES = [
  '/',
  '/medicines',
  '/generics',
  '/companies',
  '/drug-classes',
  '/dosage-forms',
  '/conditions',
  '/new-medicines',
  '/about',
  '/editorial-policy',
  '/medical-reviewers',
  '/contact',
  '/disclaimer',
  '/terms',
  '/privacy',
  '/sitemap',
];

/** Letters a–z that start at least one slug (empty letter pages are noindex, so they're left out). */
const lettersOf = (rows: SitemapRow[]) =>
  [...new Set(rows.map((r) => r.slug[0]).filter((c) => c >= 'a' && c <= 'z'))].sort();

type Url = { loc: string; lastmod?: string | null; images?: string[] };

const esc = (s: string) =>
  s
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
const day = (d?: string | null) => (d && /^\d{4}-\d{2}-\d{2}/.test(d) ? d.slice(0, 10) : null);
const abs = (site: string, path: string) =>
  /^https?:\/\//.test(path) ? path : `${site}${path === '/' ? '/' : path}`;

function urlset(site: string, urls: Url[]) {
  const body = urls
    .map((u) => {
      const lastmod = day(u.lastmod);
      const images = (u.images ?? [])
        .filter(Boolean)
        .map((i) => `<image:image><image:loc>${esc(abs(site, i))}</image:loc></image:image>`)
        .join('');
      return `  <url><loc>${esc(abs(site, u.loc))}</loc>${lastmod ? `<lastmod>${lastmod}</lastmod>` : ''}${images}</url>`;
    })
    .join('\n');
  return (
    '<?xml version="1.0" encoding="UTF-8"?>\n' +
    '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">\n' +
    `${body}\n</urlset>\n`
  );
}

/** Splits a list into numbered files of at most MAX_URLS (always at least one file). */
function chunked(prefix: string, urls: Url[], out: Map<string, Url[]>, max = MAX_URLS) {
  const n = Math.max(1, Math.ceil(urls.length / max));
  for (let i = 0; i < n; i++) out.set(`${prefix}-${i + 1}.xml`, urls.slice(i * max, (i + 1) * max));
}

const newest = (urls: Url[]) =>
  urls
    .map((u) => day(u.lastmod))
    .filter(Boolean)
    .sort()
    .pop();

/** Builds every sitemap file: Map of file name → XML (including `sitemap.xml`, the index). */
export async function buildSitemaps(source: SitemapSource, site: string, max = MAX_URLS) {
  const [brands, generics, companies, classes, forms, indications, reviewers, vet, agro] = await Promise.all([
    source.brands(),
    source.generics(),
    source.companies(),
    source.drugClasses(),
    source.dosageForms(),
    source.indications(),
    source.reviewers(),
    source.catalogueProducts('vet'),
    source.catalogueProducts('agro'),
  ]);
  const files = new Map<string, Url[]>();
  const brandUrl = (b: SitemapRow, prefix = ''): Url => ({
    loc: `${prefix}/brand/${b.slug}`,
    lastmod: b.lastmod,
    images: b.image ? [b.image] : [],
  });

  chunked(
    'sitemap-brands',
    brands.map((b) => brandUrl(b)),
    files,
    max,
  );
  const bnBrands = brands.filter((b) => b.bn).map((b) => ({ ...brandUrl(b, '/bn'), images: [] }));
  if (bnBrands.length) chunked('sitemap-bn-brands', bnBrands, files, max);
  files.set(
    'sitemap-generics.xml',
    generics.flatMap((g) => [
      { loc: `/generic/${g.slug}`, lastmod: g.lastmod },
      { loc: `/generic/${g.slug}/brands`, lastmod: g.lastmod },
    ]),
  );
  const bnGenerics = generics.filter((g) => g.bn);
  if (bnGenerics.length)
    files.set(
      'sitemap-bn-generics.xml',
      bnGenerics.map((g) => ({ loc: `/generic/${g.slug}/bn`, lastmod: g.lastmod })),
    );
  files.set(
    'sitemap-companies.xml',
    companies.map((c) => ({ loc: `/company/${c.slug}`, lastmod: c.lastmod })),
  );
  files.set('sitemap-taxonomy.xml', [
    ...classes.map((c) => ({ loc: `/drug-class/${c.slug}`, lastmod: c.lastmod })),
    ...forms.map((f) => ({ loc: `/dosage-form/${f.slug}`, lastmod: f.lastmod })),
    ...indications.map((c) => ({ loc: `/indication/${c.slug}`, lastmod: c.lastmod })),
  ]);
  const product =
    (cat: string) =>
    (r: SitemapRow): Url => ({
      loc: `/${cat}/brand/${r.slug}`,
      lastmod: r.lastmod,
      images: r.image ? [r.image] : [],
    });
  files.set('sitemap-vet.xml', [{ loc: '/vet' }, ...vet.map(product('vet'))]);
  files.set('sitemap-agro.xml', [{ loc: '/agro' }, ...agro.map(product('agro'))]);
  files.set('sitemap-pages.xml', [
    ...STATIC_PAGES.map((loc) => ({ loc })),
    ...reviewers.map((r) => ({ loc: `/reviewer/${r.slug}`, lastmod: r.lastmod })),
    ...lettersOf(brands).map((l) => ({ loc: `/medicines/letter/${l}` })),
    ...lettersOf(generics).map((l) => ({ loc: `/generics/letter/${l}` })),
    ...lettersOf(indications).map((l) => ({ loc: `/conditions/letter/${l}` })),
  ]);

  const xml = new Map<string, string>();
  const index: string[] = [];
  for (const [name, urls] of files) {
    xml.set(name, urlset(site, urls));
    const lastmod = newest(urls);
    index.push(
      `  <sitemap><loc>${esc(`${site}/${name}`)}</loc>${lastmod ? `<lastmod>${lastmod}</lastmod>` : ''}</sitemap>`,
    );
  }
  xml.set(
    'sitemap.xml',
    '<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n' +
      `${index.join('\n')}\n</sitemapindex>\n`,
  );
  return xml;
}

/** robots.txt: everything public is allowed; API, admin and internal search results are not. */
export const robotsTxt = (site: string) =>
  [
    'User-agent: *',
    'Allow: /',
    'Disallow: /api/',
    'Disallow: /admin',
    'Disallow: /search',
    'Disallow: /saved',
    '',
    `Sitemap: ${site}/sitemap.xml`,
    '',
  ].join('\n');
