import { describe, expect, it } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {
  PATCH_RING_DEPTH,
  listPatchVersions,
  snapshotCurrent,
  writeVersionFile,
} from '../src/server/update';

describe('Part 7d patch ring buffer', () => {
  it(`keeps the last ${PATCH_RING_DEPTH} snapshots and evicts older ones`, () => {
    const root = fs.mkdtempSync(path.join(os.tmpdir(), 'rha-patches-'));
    fs.mkdirSync(path.join(root, 'src'), { recursive: true });
    fs.writeFileSync(path.join(root, 'src', 'version.ts'), "export const VERSION = 'V1.10a';\n");
    fs.writeFileSync(path.join(root, 'keep.txt'), 'seed\n');

    const versions = ['V1.10a', 'V1.10b', 'V1.10c', 'V1.10d', 'V1.10e', 'V1.10f', 'V1.11'];
    for (const v of versions) {
      writeVersionFile(root, v);
      fs.writeFileSync(path.join(root, 'keep.txt'), `${v}\n`);
      snapshotCurrent(root, v);
    }

    const kept = listPatchVersions(root);
    expect(kept).toHaveLength(PATCH_RING_DEPTH);
    expect(kept[0]).toBe('V1.10c'); // oldest kept after evicting a+b
    expect(kept[kept.length - 1]).toBe('V1.11');
    expect(fs.existsSync(path.join(root, 'patches', 'V1.10a'))).toBe(false);
    expect(fs.existsSync(path.join(root, 'patches', 'V1.10b'))).toBe(false);
    expect(fs.existsSync(path.join(root, 'patches', 'V1.11', 'keep.txt'))).toBe(true);

    fs.rmSync(root, { recursive: true, force: true });
  });
});
