import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import express from 'express';
import request from 'supertest';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { clearMemoryCache } from '../src/middleware/cache';
import { canonicalPath, inlineCss, websiteRouter } from '../src/ssr/website';
import { withMonitoringTags } from '../src/seo/monitoring';

/** A fake website build: same files and `render` contract as website/dist. */
let dist: string;
let calls = 0;
const notFound: string[] = [];
beforeAll(() => {
  dist = fs.mkdtempSync(path.join(os.tmpdir(), 'bdm-site-'));
  fs.mkdirSync(path.join(dist, 'client', 'assets'), { recursive: true });
  fs.mkdirSync(path.join(dist, 'server'));
  fs.writeFileSync(
    path.join(dist, 'client', 'index.html'),
    '<!doctype html><html lang="en"><head><!--app-head--></head><body><div id="root"><!--app-html--></div><!--app-data--></body></html>',
  );
  fs.writeFileSync(path.join(dist, 'client', 'assets', 'app-abc123.js'), 'console.log(1)');
  fs.writeFileSync(
    path.join(dist, 'server', 'entry-server.mjs'),
    `globalThis.__renders = 0;
export const createLocalClient = () => ({});
export const createLocalSitemapSource = () => ({
  brands: async () => [{ slug: 'napa-500-mg-tablet', lastmod: '2026-11-01', image: null, bn: true }],
  generics: async () => [], companies: async () => [], drugClasses: async () => [], dosageForms: async () => [], indications: async () => [],
reviewers: async () => [],
  catalogueProducts: async () => [],
});
export async function render(url) {
  globalThis.__renders++;
  const p = new URL(url).pathname;
  if (p === '/old') return { kind: 'redirect', status: 301, location: '/brand/new' };
  if (p === '/boom') throw new Error('render failed');
  const status = p === '/missing' ? 404 : 200;
  return { kind: 'page', status, head: '<title>T ' + p + '</title>', htmlAttrs: p === '/bn' ? 'lang="bn"' : '',
    html: '<h1>' + p + '</h1>', data: '{"loaderData":{}}' };
}`,
  );
  const r = websiteRouter(
    dist,
    'json',
    (href) => import(/* @vite-ignore */ href),
    'https://www.bdmedicine.com',
    { onNotFound: (req) => notFound.push(req.originalUrl) },
  );
  if (!r) throw new Error('router not created');
  app.use((req, res, next) =>
    req.path.startsWith('/api/') ? res.status(404).json({ api: true }) : r(req, res, next),
  );
});
afterAll(() => fs.rmSync(dist, { recursive: true, force: true }));
const app = express();
const renders = () => (globalThis as unknown as { __renders: number }).__renders;

describe('website server rendering', () => {
  it('renders full HTML with head, body and the hydration data', async () => {
    const res = await request(app).get('/brand/napa');
    expect(res.status).toBe(200);
    expect(res.headers['content-type']).toMatch(/html/);
    expect(res.text).toContain('<title>T /brand/napa</title>');
    expect(res.text).toContain('<h1>/brand/napa</h1>');
    expect(res.text).toContain(
      '<script id="__INITIAL_DATA__" type="application/json">{"loaderData":{}}</script>',
    );
  });

  it('sends real status codes: 404, 301 and 500', async () => {
    expect((await request(app).get('/missing')).status).toBe(404);
    const moved = await request(app).get('/old');
    expect(moved.status).toBe(301);
    expect(moved.headers.location).toBe('/brand/new');
    const err = await request(app).get('/boom');
    expect(err.status).toBe(500);
    expect(err.text).toContain('noindex');
  });

  it('sets <html lang> from the page', async () => {
    expect((await request(app).get('/bn')).text).toContain('<html lang="bn">');
  });

  it('caches rendered pages and clears the cache after admin writes', async () => {
    await request(app).get('/cached');
    calls = renders();
    const again = await request(app).get('/cached');
    expect(again.headers['x-cache']).toBe('HIT');
    expect(renders()).toBe(calls);
    clearMemoryCache(); // what every admin write calls
    const fresh = await request(app).get('/cached');
    expect(fresh.headers['x-cache']).toBe('MISS');
    expect(renders()).toBe(calls + 1);
  });

  it('serves hashed assets with a long cache and leaves /api alone', async () => {
    const a = await request(app).get('/assets/app-abc123.js');
    expect(a.status).toBe(200);
    expect(a.headers['cache-control']).toContain('immutable');
    expect((await request(app).get('/api/v1/nope')).body).toEqual({ api: true });
  });

  it('301s to one clean address: no trailing slash, capitals or double slashes', async () => {
    expect(canonicalPath('/Brand/Napa-500-mg//')).toBe('/brand/napa-500-mg');
    expect(canonicalPath('/')).toBe('/');
    const res = await request(app).get('/Brand/Napa/?q=1');
    expect(res.status).toBe(301);
    expect(res.headers.location).toBe('/brand/napa?q=1');
    expect((await request(app).get('/brand/napa/')).headers.location).toBe('/brand/napa');
    // hashed asset names keep their capitals
    expect((await request(app).get('/assets/app-abc123.js')).status).toBe(200);
  });

  it('serves robots.txt and the sitemaps from the data (not the page renderer)', async () => {
    const robots = await request(app).get('/robots.txt');
    expect(robots.status).toBe(200);
    expect(robots.text).toContain('Sitemap: https://www.bdmedicine.com/sitemap.xml');
    const index = await request(app).get('/sitemap.xml');
    expect(index.status).toBe(200);
    expect(index.headers['content-type']).toMatch(/xml/);
    expect(index.text).toContain('https://www.bdmedicine.com/sitemap-brands-1.xml');
    const brands = await request(app).get('/sitemap-brands-1.xml');
    expect(brands.text).toContain('https://www.bdmedicine.com/brand/napa-500-mg-tablet');
    expect((await request(app).get('/sitemap-bn-brands-1.xml')).text).toContain(
      '/bn/brand/napa-500-mg-tablet',
    );
    expect((await request(app).get('/sitemap-nope-9.xml')).status).toBe(404);
  });

  it('inlines the small stylesheet instead of a render-blocking request (Phase 11)', () => {
    fs.writeFileSync(path.join(dist, 'client', 'assets', 'index-abc.css'), 'body{color:red}');
    const html = inlineCss(
      '<head><link rel="stylesheet" crossorigin href="/assets/index-abc.css"></head>',
      path.join(dist, 'client'),
    );
    expect(html).toBe('<head><style data-href="/assets/index-abc.css">body{color:red}</style></head>');
    // missing or too-large files keep the <link>
    expect(inlineCss('<link rel="stylesheet" href="/assets/nope.css">', path.join(dist, 'client'))).toContain(
      '<link',
    );
    expect(
      inlineCss('<link rel="stylesheet" href="/assets/index-abc.css">', path.join(dist, 'client'), 5),
    ).toContain('<link');
  });

  it('records every 404, also when it comes from the page cache (Phase 13)', async () => {
    notFound.length = 0;
    await request(app).get('/missing?x=1');
    await request(app).get('/missing?x=1');
    await request(app).get('/brand/napa');
    expect(notFound).toEqual(['/missing?x=1', '/missing?x=1']);
  });
});

describe('monitoring tags (Phase 13)', () => {
  const tpl = '<html><head><title>x</title></head><body></body></html>';
  it('adds nothing when the env variables are empty', () => {
    expect(withMonitoringTags(tpl, {})).toBe(tpl);
  });
  it('adds the Search Console meta and a deferred analytics script', () => {
    const out = withMonitoringTags(tpl, {
      gsc: 'abc"123',
      plausibleDomain: 'bdmedicine.com',
      plausibleSrc: 'https://plausible.io/js/script.js',
    });
    expect(out).toContain('<meta name="google-site-verification" content="abc&quot;123" />');
    expect(out).toContain(
      '<script defer data-domain="bdmedicine.com" src="https://plausible.io/js/script.js"></script>',
    );
    expect(out.indexOf('google-site-verification')).toBeLessThan(out.indexOf('</head>'));
  });
});
