import { afterEach, describe, expect, test, vi } from 'vitest';

const load = async () => {
  vi.resetModules();
  process.env.SPOON_WORKER_TOKEN = 'test-worker-token';
  process.env.GITHUB_APP_ID = '123';
  process.env.GITHUB_APP_PRIVATE_KEY =
    '-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----';
  return await import('../../src/worker');
};

describe('planWorkdirCleanup', () => {
  afterEach(() => vi.resetModules());

  test('never removes the homes/ root or any home directory', async () => {
    const { planWorkdirCleanup } = await load();
    const plan = planWorkdirCleanup({
      root: '/work',
      rootEntries: [{ name: 'homes', isDirectory: true }],
      homesEntries: { alice: [{ name: 'Code', isDirectory: true }] },
      codeLeaves: {},
      activeWorkdirs: new Set(),
      runningBoxUsernames: new Set(),
    });
    expect(plan.removeDirs).not.toContain('/work/homes');
    expect(plan.removeDirs).not.toContain('/work/homes/alice');
  });

  test('removes legacy top-level job dirs not in the active set', async () => {
    const { planWorkdirCleanup } = await load();
    const plan = planWorkdirCleanup({
      root: '/work',
      rootEntries: [
        { name: 'homes', isDirectory: true },
        { name: 'legacy-job-123', isDirectory: true },
        { name: 'dev', isDirectory: true },
      ],
      homesEntries: {},
      codeLeaves: {},
      activeWorkdirs: new Set(['/work/dev']),
      runningBoxUsernames: new Set(),
    });
    expect(plan.removeDirs).toContain('/work/legacy-job-123');
    expect(plan.removeDirs).not.toContain('/work/dev');
    expect(plan.removeDirs).not.toContain('/work/homes');
  });

  test('removes per-thread checkouts only for users with no running box', async () => {
    const { planWorkdirCleanup } = await load();
    const plan = planWorkdirCleanup({
      root: '/work',
      rootEntries: [{ name: 'homes', isDirectory: true }],
      homesEntries: {
        alice: [{ name: 'Code', isDirectory: true }],
        bob: [{ name: 'Code', isDirectory: true }],
      },
      codeLeaves: {
        alice: ['/work/homes/alice/Code/spoon-a/branch-x'],
        bob: ['/work/homes/bob/Code/spoon-b/branch-y'],
      },
      activeWorkdirs: new Set(),
      runningBoxUsernames: new Set(['bob']),
    });
    expect(plan.removeDirs).toContain(
      '/work/homes/alice/Code/spoon-a/branch-x',
    );
    expect(plan.removeDirs).not.toContain(
      '/work/homes/bob/Code/spoon-b/branch-y',
    );
    expect(plan.removeDirs).not.toContain('/work/homes/alice');
    expect(plan.removeDirs).not.toContain('/work/homes/alice/Code');
  });
});
