import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { createCleanupService } from './mindspace-cleanup.mjs';

test('lists workspace temp files for cleanup', async () => {
  const h5Root = await fs.mkdtemp(path.join(os.tmpdir(), 'mindspace-cleanup-'));
  const storageRoot = path.join(h5Root, 'data', 'mindspace');
  const username = 'john';
  const tempFile = path.join(h5Root, 'temp', username, 'draft.html');
  await fs.mkdir(path.dirname(tempFile), { recursive: true });
  await fs.writeFile(tempFile, '<html></html>');

  const pool = {
    query: async () => [[], []],
  };
  const cleanup = createCleanupService(pool, { h5Root, storageRoot });
  const items = await cleanup.listCandidates('user-1', username);
  assert.equal(items.length, 1);
  assert.equal(items[0].kind, 'workspace_temp');
  assert.equal(items[0].label, 'draft.html');
});

test('lists stale page versions for cleanup', async () => {
  const pool = {
    query: async (sql, params) => {
      if (sql.includes('FROM h5_upload_sessions')) return [[], []];
      if (sql.includes('FROM h5_page_versions pv')) {
        return [
          [
            {
              version_id: 'ver-old',
              page_id: 'page-1',
              version_no: 2,
              content_asset_id: 'asset-old',
              bundle_asset_id: null,
              title: 'Demo Page',
              size_bytes: 4096,
              display_name: 'Demo Page · v2',
              created_at: 1000,
              bundle_size_bytes: 0,
            },
          ],
          [],
        ];
      }
      return [[], []];
    },
  };
  const cleanup = createCleanupService(pool, { h5Root: os.tmpdir(), storageRoot: os.tmpdir() });
  const items = await cleanup.listCandidates('user-1', 'john');
  const stale = items.filter((item) => item.kind === 'stale_page_version');
  assert.equal(stale.length, 1);
  assert.equal(stale[0].sizeBytes, 4096);
  assert.match(stale[0].label, /Demo Page · v2/);
});
