/**
 * J3 — Verification integrity regression.
 * Suites named *-test.ts (not *.test.ts) must still be collected; 0-collected
 * runs must never report ok/green.
 *
 * Workspace must live under the repo (not os.tmpdir) so vitest resolves via
 * upward node_modules lookup — same as real jobs under workspaces/.
 */
import { describe, it, expect } from 'vitest';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { scaffoldWorkspace, runVitest } from '../src/core/sandbox';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const FIXTURES = path.join(ROOT, 'workspaces', '_j3-fixtures');

function freshDir(name: string): string {
  const dir = path.join(FIXTURES, `${name}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
  fs.mkdirSync(dir, { recursive: true });
  return dir;
}

describe('J3 collection integrity', () => {
  it('collects and executes suites named tests/foo-bar-test.ts', () => {
    const dir = freshDir('collect');
    try {
      scaffoldWorkspace(dir, 'j3-collect');
      fs.writeFileSync(
        path.join(dir, 'tests', 'foo-bar-test.ts'),
        [
          "import { describe, it, expect } from 'vitest';",
          "describe('foo-bar', () => {",
          "  it('a', () => { expect(1).toBe(1); });",
          "  it('b', () => { expect(2).toBe(2); });",
          "  it('c', () => { expect(3).toBe(3); });",
          '});',
          '',
        ].join('\n'),
      );
      const run = runVitest(dir);
      expect(run.collected).toBeGreaterThanOrEqual(1);
      expect(run.passed + run.failed).toBe(3);
      expect(run.ok).toBe(true);
    } finally {
      fs.rmSync(dir, { recursive: true, force: true });
    }
  });

  it('0-collected suite yields a failing run (never green)', () => {
    const dir = freshDir('zero');
    try {
      scaffoldWorkspace(dir, 'j3-zero');
      // Empty tests/ — vitest collects nothing. ok must be false (never green).
      const run = runVitest(dir);
      expect(run.collected).toBe(0);
      expect(run.passed).toBe(0);
      expect(run.ok).toBe(false);
    } finally {
      fs.rmSync(dir, { recursive: true, force: true });
    }
  });
});
