import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { mkdtemp, writeFile } from 'fs/promises';
import * as os from 'os';
import * as path from 'path';
import { checkWorkflowHealth } from '../check-workflow-health.ts';

describe('check-workflow-health', () => {
  let consoleSpy: any;

  beforeEach(() => {
    consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
  });

  afterEach(() => {
    consoleSpy.mockRestore();
  });

  it('maps status values to expected health outcomes', async () => {
    const dir = await mkdtemp(path.join(os.tmpdir(), 'workflow-health-test-'));

    const cases: Array<{ status: string; expectedCode: number; expectedOk: boolean }> = [
      { status: 'idle', expectedCode: 0, expectedOk: true },
      { status: 'running', expectedCode: 0, expectedOk: true },
      { status: 'completed', expectedCode: 0, expectedOk: true },
      { status: 'failed', expectedCode: 1, expectedOk: false },
      { status: 'blocked', expectedCode: 1, expectedOk: false },
    ];

    for (const c of cases) {
      const statusPath = path.join(dir, `${c.status}.json`);
      await writeFile(statusPath, JSON.stringify({ overallStatus: c.status }), 'utf8');

      const code = await checkWorkflowHealth(statusPath);
      expect(code).toBe(c.expectedCode);

      const lastOutput = consoleSpy.mock.calls.at(-1)?.[0] as string;
      expect(JSON.parse(lastOutput)).toMatchObject({ ok: c.expectedOk, status: c.status });
    }
  });
});
