import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { ADMIN_TOKEN, adminServer } from './admin-helpers.ts';

describe('/v1/admin: доступ (спека хостинга 5.1)', () => {
  it('нет admin в конфиге — 404 на любой путь', async () => {
    const { app } = await adminServer({ admin: false });
    for (const url of ['/v1/admin/office', '/v1/admin/nope'])
      expect((await app.inject({ url, headers: { authorization: `Bearer ${ADMIN_TOKEN}` } })).statusCode).toBe(404);
  });
  it('чужой токен, токен зрителя, токен источника — 401', async () => {
    const { app } = await adminServer();
    const tries = [
      { url: '/v1/admin/office' },
      { url: '/v1/admin/office', headers: { authorization: 'Bearer nope-nope-nope' } },
      { url: '/v1/admin/office', headers: { authorization: 'Bearer demo-viewer-token' } },
      { url: '/v1/admin/office?token=demo-viewer-token' },
      { url: '/v1/admin/office', headers: { authorization: 'Bearer demo-hook-token' } },
    ];
    for (const t of tries) {
      const r = await app.inject(t);
      expect([r.statusCode, r.json()], JSON.stringify(t)).toEqual([401, { error: 'unauthorized' }]);
    }
  });
  it('схема Bearer без учёта регистра; неизвестный путь — 404 JSON', async () => {
    const { app } = await adminServer();
    expect((await app.inject({ url: '/v1/admin/office', headers: { authorization: `bearer ${ADMIN_TOKEN}` } })).statusCode).toBe(200);
    const r = await app.inject({ url: '/v1/admin/nope', headers: { authorization: `Bearer ${ADMIN_TOKEN}` } });
    expect([r.statusCode, r.json()]).toEqual([404, { error: 'not_found' }]);
  });
  it('края /v1/admin — ответы API: /v1/admin без слеша 404 JSON, битый JSON на неизвестный путь 400 JSON', async () => {
    const { app, auth } = await adminServer();
    const bare = await app.inject({ url: '/v1/admin', headers: auth });
    expect([bare.statusCode, bare.json()]).toEqual([404, { error: 'not_found' }]);
    expect((await app.inject({ url: '/v1/admin' })).statusCode).toBe(401);
    const broken = await app.inject({ method: 'POST', url: '/v1/admin/nope', headers: { ...auth, 'content-type': 'application/json' }, payload: '{нет' });
    expect([broken.statusCode, broken.json()]).toEqual([400, { error: 'invalid', message: 'тело запроса — не JSON' }]);
  });
  it('путь с %2F под /v1/admin не обходит проверку зрителя у статики; HEAD без токена — 401', async () => {
    // /v1/admin%2F… роутер отдаёт статике (/*), а не плагину admin: раньше общий крюк пропускал такой путь без
    // проверки зрителя по декодированной строке (ответ 404 или 403 статики), теперь — 401, как у любого файла зрителя.
    const dist = mkdtempSync(join(tmpdir(), 'po-dist-'));
    mkdirSync(join(dist, 'v1', 'admin'), { recursive: true });
    writeFileSync(join(dist, 'index.html'), '<html></html>');
    writeFileSync(join(dist, 'v1', 'admin', 'secret.txt'), 'секрет');
    const { app } = await adminServer({ viewerDist: dist });
    for (const url of ['/v1/admin%2Fsecret.txt', '/v1/admin%2F..%2F..%2Findex.html']) {
      const r = await app.inject({ url });
      expect([url, r.statusCode]).toEqual([url, 401]);
    }
    expect((await app.inject({ method: 'HEAD', url: '/v1/admin/office' })).statusCode).toBe(401);
  });
  it('кодированный путь (%61 → a) не обходит токен администратора', async () => {
    const { app, auth } = await adminServer();
    // Cookie зрителя и токен зрителя в query — не доступ администратора, на любом написании пути.
    for (const url of ['/v1/%61dmin/office', '/v1/%61dmin/status']) {
      const byCookie = await app.inject({ url, headers: { cookie: 'po_viewer=demo-viewer-token' } });
      expect([url, byCookie.statusCode, byCookie.json()]).toEqual([url, 401, { error: 'unauthorized' }]);
      const byQuery = await app.inject({ url: `${url}?token=demo-viewer-token` });
      expect([url, byQuery.statusCode, byQuery.json()]).toEqual([url, 401, { error: 'unauthorized' }]);
    }
    expect((await app.inject({ url: '/v1/%61dmin/office', headers: auth })).statusCode).toBe(200);
    expect((await app.inject({ url: '/v1/%61dmin/status', headers: auth })).statusCode).toBe(200);
  });
});

describe('/v1/admin: чтение (спека хостинга 5.2, 5.6)', () => {
  it('GET office — версия и четыре файла, логотип base64', async () => {
    const { app, auth } = await adminServer();
    const r = await app.inject({ url: '/v1/admin/office', headers: auth });
    const body = r.json();
    expect(body.version).toBe(1);
    expect(Object.keys(body.files).sort()).toEqual(['logo.png', 'office.yaml', 'people.yaml', 'rules.yaml']);
    expect(typeof body.files['logo.png']).toBe('string');
  });
  it('GET versions и versions/:n', async () => {
    const { app, auth } = await adminServer();
    const list = (await app.inject({ url: '/v1/admin/versions', headers: auth })).json();
    expect(list).toEqual([{ version: 1, at: expect.any(String), kind: 'initial' }]);
    const one = (await app.inject({ url: '/v1/admin/versions/1', headers: auth })).json();
    expect(one).toMatchObject({ version: 1, kind: 'initial', files: { 'rules.yaml': expect.any(String) } });
    expect((await app.inject({ url: '/v1/admin/versions/9', headers: auth })).statusCode).toBe(404);
    for (const n of ['1.0', '0x1', '1e0', '01x'])
      expect([n, (await app.inject({ url: `/v1/admin/versions/${n}`, headers: auth })).statusCode]).toEqual([n, 404]);
  });
  it('GET status — строки, как у CLI status --all', async () => {
    const { app, auth } = await adminServer();
    const rows = (await app.inject({ url: '/v1/admin/status', headers: auth })).json();
    expect(rows.find((x: { id: string }) => x.id === 'p1')).toMatchObject({ kind: 'human', name: 'Стас', status: 'offline', source: null });
  });
  it('картинка предпросмотра: есть — image/png, нет — 404', async () => {
    const { app, auth, previews } = await adminServer();
    const id = previews.put({ plain: Buffer.from('p'), grid: Buffer.from('g') });
    const r = await app.inject({ url: `/v1/admin/preview/${id}/grid.png`, headers: auth });
    expect([r.statusCode, r.headers['content-type'], r.body]).toEqual([200, 'image/png', 'g']);
    expect((await app.inject({ url: '/v1/admin/preview/nope/plain.png', headers: auth })).statusCode).toBe(404);
    expect((await app.inject({ url: `/v1/admin/preview/${id}` + '/other.png', headers: auth })).statusCode).toBe(404);
  });
});
