import { describe, expect, it } from 'vitest';
import request from 'supertest';
import { buildSitemaps, robotsTxt, STATIC_PAGES, type SitemapSource } from '../src/seo/sitemap';
import { createApp } from '../src/app';

const SITE = 'https://www.bdmedicine.com';
const source = (brandCount: number): SitemapSource => ({
  brands: async () =>
    Array.from({ length: brandCount }, (_, i) => ({
      slug: `brand-${i + 1}`,
      lastmod: '2026-11-0' + ((i % 9) + 1),
      image: i === 0 ? 'https://img.bdmedicine.com/brands/brand-1.webp' : null,
      bn: i < 2,
    })),
  generics: async () => [
    { slug: 'paracetamol', lastmod: '2026-11-21', bn: true },
    { slug: 'omeprazole', lastmod: null, bn: false },
  ],
  companies: async () => [{ slug: 'beximco-pharmaceuticals', lastmod: '2026-10-01' }],
  drugClasses: async () => [{ slug: 'proton-pump-inhibitors' }],
  dosageForms: async () => [{ slug: 'tablet' }],
  indications: async () => [{ slug: 'fever' }, { slug: 'pain-&-ache' }],
  reviewers: async () => [{ slug: 'jane-doe', lastmod: '2026-11-15' }],
  catalogueProducts: async (cat) =>
    cat === 'vet' ? [{ slug: 'renamycin-10-percent-injection', lastmod: '2026-11-10', image: null }] : [],
});

describe('sitemaps', () => {
  it('builds an index of every child sitemap, with lastmod', async () => {
    const xml = await buildSitemaps(source(3), SITE);
    const index = xml.get('sitemap.xml')!;
    expect(index).toContain('<sitemapindex');
    for (const name of [
      'sitemap-brands-1.xml',
      'sitemap-bn-brands-1.xml',
      'sitemap-generics.xml',
      'sitemap-bn-generics.xml',
      'sitemap-companies.xml',
      'sitemap-taxonomy.xml',
      'sitemap-vet.xml',
      'sitemap-agro.xml',
      'sitemap-pages.xml',
    ]) {
      expect(xml.has(name)).toBe(true);
      expect(index).toContain(`<loc>${SITE}/${name}</loc>`);
    }
    expect(index).toContain(`<loc>${SITE}/sitemap-generics.xml</loc><lastmod>2026-11-21</lastmod>`);
  });

  it('splits brands into files of at most the limit (40,000 in production)', async () => {
    const xml = await buildSitemaps(source(5), SITE, 2);
    expect([...xml.keys()].filter((k) => k.startsWith('sitemap-brands-'))).toEqual([
      'sitemap-brands-1.xml',
      'sitemap-brands-2.xml',
      'sitemap-brands-3.xml',
    ]);
    const count = (s: string) => (s.match(/<url>/g) ?? []).length;
    expect(count(xml.get('sitemap-brands-1.xml')!)).toBe(2);
    expect(count(xml.get('sitemap-brands-3.xml')!)).toBe(1);
  });

  it('brand entries carry lastmod and the pack image; Bangla entries only where a Bangla page exists', async () => {
    const xml = await buildSitemaps(source(3), SITE);
    const brands = xml.get('sitemap-brands-1.xml')!;
    expect(brands).toContain('xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"');
    expect(brands).toContain(
      `<url><loc>${SITE}/brand/brand-1</loc><lastmod>2026-11-01</lastmod><image:image><image:loc>https://img.bdmedicine.com/brands/brand-1.webp</image:loc></image:image></url>`,
    );
    expect(brands).toContain(`<url><loc>${SITE}/brand/brand-2</loc><lastmod>2026-11-02</lastmod></url>`);
    const bn = xml.get('sitemap-bn-brands-1.xml')!;
    expect(bn).toContain(`${SITE}/bn/brand/brand-1`);
    expect(bn).toContain(`${SITE}/bn/brand/brand-2`);
    expect(bn).not.toContain('brand-3');
    expect(xml.get('sitemap-bn-generics.xml')).toContain(`${SITE}/bn/generic/paracetamol`);
    expect(xml.get('sitemap-bn-generics.xml')).not.toContain('omeprazole');
    expect(xml.get('sitemap-generics.xml')).toContain(`${SITE}/generic/omeprazole/brands`);
  });

  it('escapes XML and lists the hubs and information pages', async () => {
    const xml = await buildSitemaps(source(1), SITE);
    expect(xml.get('sitemap-taxonomy.xml')).toContain(`${SITE}/indication/pain-&amp;-ache`);
    const pages = xml.get('sitemap-pages.xml')!;
    // hubs + one letter page per letter that has entries: medicines b, generics o/p, conditions f/p
    expect((pages.match(/<url>/g) ?? []).length).toBe(STATIC_PAGES.length + 5 + 1); // + 1 reviewer profile
    expect(pages).toContain(`${SITE}/reviewer/jane-doe</loc><lastmod>2026-11-15</lastmod>`);
    expect(pages).toContain(`${SITE}/editorial-policy`);
    expect(pages).toContain(`${SITE}/medicines/letter/b</loc>`);
    expect(pages).not.toContain('/medicines/letter/q');
    expect(pages).toContain(`<loc>${SITE}/</loc>`);
    expect(xml.get('sitemap-vet.xml')).toContain(`${SITE}/vet</loc>`);
    expect(xml.get('sitemap-vet.xml')).toContain(
      `${SITE}/vet/brand/renamycin-10-percent-injection</loc><lastmod>2026-11-10</lastmod>`,
    ); // Phase 12 product pages
    expect(xml.get('sitemap-agro.xml')).toContain(`${SITE}/agro</loc>`);
  });

  it('no Bangla sitemaps when nothing has Bangla text', async () => {
    const s = source(2);
    const xml = await buildSitemaps(
      {
        ...s,
        brands: async () => (await s.brands()).map((b) => ({ ...b, bn: false })),
        generics: async () => [],
      },
      SITE,
    );
    expect(xml.has('sitemap-bn-brands-1.xml')).toBe(false);
    expect(xml.has('sitemap-bn-generics.xml')).toBe(false);
  });
});

describe('robots.txt and noindex headers', () => {
  it('allows public pages, blocks API, admin and search results, and points to the sitemap', () => {
    const txt = robotsTxt(SITE);
    expect(txt).toContain('User-agent: *\nAllow: /');
    for (const d of ['/api/', '/admin', '/search']) expect(txt).toContain(`Disallow: ${d}`);
    expect(txt).toContain(`Sitemap: ${SITE}/sitemap.xml`);
  });

  it('every API response says X-Robots-Tag: noindex', async () => {
    const app = createApp({ ping: async () => true, website: false });
    const health = await request(app).get('/api/v1/health');
    expect(health.headers['x-robots-tag']).toBe('noindex, nofollow');
    const missing = await request(app).get('/api/v1/nope');
    expect(missing.headers['x-robots-tag']).toBe('noindex, nofollow');
  });
});
