import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, rmSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { resolveTaskWorkspaceDir, ensureWorkspaceDirs } from './workspace-resolver.js';

describe('resolveTaskWorkspaceDir', () => {
  const wt = '/wt';
  const space = { kind: 'case' as const, id: 'sp-1', ownerId: 'u1' };

  it('persistent mode → the space files dir (shared tree)', () => {
    expect(resolveTaskWorkspaceDir('persistent', space, wt, 42)).toBe('/wt/space/sp-1/files');
  });
  it('ephemeral mode → a per-task throwaway dir', () => {
    expect(resolveTaskWorkspaceDir('ephemeral', space, wt, 42)).toBe('/wt/ephemeral/42');
  });
  it('persistent with a personal space → that personal space files dir', () => {
    const personal = { kind: 'personal' as const, id: 'sp-p', ownerId: 'u1' };
    expect(resolveTaskWorkspaceDir('persistent', personal, wt, 7)).toBe('/wt/space/sp-p/files');
  });
});

describe('ensureWorkspaceDirs', () => {
  let dir: string;
  beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'ws-')); });
  afterEach(() => { rmSync(dir, { recursive: true, force: true }); });
  it('creates the workspace + input/output/logs subdirs', () => {
    const ws = join(dir, 'space', 'sp', 'files');
    ensureWorkspaceDirs(ws);
    for (const sub of ['input', 'output', 'logs']) expect(existsSync(join(ws, sub))).toBe(true);
  });
});
