import http from 'node:http';
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { buildServer } from '../src/index.ts';
import { makeRuntime } from './helpers.ts';

// Заголовки кеша статики (todo 32): атлас каталога и файлы вьюера с постоянными именами — ревалидация
// (no-cache + ETag → 304 без перекачки), хешированные бандлы Vite (/assets/*) — год immutable.
// Запросы — сырым node:http: fetch (undici) сам добавляет cache-control: no-cache, а ревалидация по RFC
// в этом случае обязана вернуть свежую копию — 304 не случится, хотя сервер работает правильно.
const TOKEN = 'demo-viewer-token';
const closers: (() => Promise<unknown>)[] = [];
afterEach(async () => {
  while (closers.length) await closers.pop()!();
});

type Answer = { status: number; headers: Record<string, string | string[] | undefined> };

async function start() {
  const { rt } = makeRuntime();
  // Каталог арта: один лист из demo-офиса.
  const assets = mkdtempSync(join(tmpdir(), 'po-cache-assets-'));
  const sheet = Object.values(rt.office.bundle.catalog.sheets)[0]!;
  mkdirSync(dirname(join(assets, sheet)), { recursive: true });
  writeFileSync(join(assets, sheet), 'png');
  // Сборка вьюера как её кладёт Vite: хешированный бандл в assets/, рядом постоянные index.html, sw.js, звуки.
  const dist = mkdtempSync(join(tmpdir(), 'po-cache-dist-'));
  mkdirSync(join(dist, 'assets'), { recursive: true });
  mkdirSync(join(dist, 'sounds'), { recursive: true });
  writeFileSync(join(dist, 'assets', 'index-DHV1uYz9.js'), 'js');
  writeFileSync(join(dist, 'index.html'), 'html');
  writeFileSync(join(dist, 'sw.js'), 'sw');
  writeFileSync(join(dist, 'sounds', 'door.ogg'), 'ogg');
  const srv = await buildServer({ runtime: rt, viewerTokens: [TOKEN], assetsDir: assets, viewerDist: dist, testMode: null });
  await srv.app.listen({ port: 0, host: '127.0.0.1' });
  closers.push(() => srv.app.close());
  const base = `http://127.0.0.1:${(srv.app.server.address() as AddressInfo).port}`;
  const get = (path: string, headers: Record<string, string> = {}): Promise<Answer> =>
    new Promise((resolve, reject) => {
      const req = http.request(`${base}${path}${path.includes('?') ? '&' : '?'}token=${TOKEN}`, { headers }, (res) => {
        res.resume();
        resolve({ status: res.statusCode ?? 0, headers: res.headers });
      });
      req.on('error', reject);
      req.end();
    });
  return { rt, get };
}

describe('заголовки кеша статики', () => {
  it('лист каталога /sprites/: no-cache и ETag, повторно с If-None-Match — 304', async () => {
    const s = await start();
    const sheet = Object.values(s.rt.office.bundle.catalog.sheets)[0]!;
    const url = '/sprites/' + sheet.split('/').map(encodeURIComponent).join('/');
    const first = await s.get(url);
    expect(first.status).toBe(200);
    expect(first.headers['cache-control']).toBe('no-cache');
    const etag = first.headers['etag'];
    expect(etag).toBeTruthy();
    const again = await s.get(url, typeof etag === 'string' ? { 'if-none-match': etag } : {});
    expect(again.status).toBe(304);
  });

  it('хешированный бандл Vite /assets/*: год immutable', async () => {
    const s = await start();
    const res = await s.get('/assets/index-DHV1uYz9.js');
    expect(res.status).toBe(200);
    expect(res.headers['cache-control']).toBe('public, max-age=31536000, immutable');
  });

  it('index.html, sw.js и звуки — имена постоянные, no-cache', async () => {
    const s = await start();
    for (const p of ['/', '/index.html', '/sw.js', '/sounds/door.ogg']) {
      const res = await s.get(p);
      expect(res.status, p).toBe(200);
      expect(res.headers['cache-control'], p).toBe('no-cache');
    }
  });
});
