import { describe, it, expect, beforeEach } from 'vitest';
import { promises as fs } from 'fs';
import path from 'path';
import {
  appendPhaseUpdate,
  getPendingPhaseUpdates,
  markPhaseUpdateSent,
  getAllPhaseUpdates,
  type PhaseUpdateEvent
} from '../PhaseUpdateQueue.js';

const TEST_QUEUE_FILE = path.join(process.cwd(), 'status/phase-updates.jsonl');

describe('PhaseUpdateQueue', () => {
  beforeEach(async () => {
    try {
      await fs.unlink(TEST_QUEUE_FILE);
    } catch {}
  });

  it('appends events and retrieves pending only', async () => {
    let ev1 = await appendPhaseUpdate({ eventType: 'phase_started', phase: 'import', summary: 'Import started' });
    let ev2 = await appendPhaseUpdate({ eventType: 'phase_failed', phase: 'import', summary: 'Import failed', details: 'Network error' });
    expect(ev1.id).toBeDefined();
    expect(ev2.id).toBeDefined();

    const pending = await getPendingPhaseUpdates();
    expect(pending.length).toBe(2);
    expect(pending.map((e: PhaseUpdateEvent) => e.id)).toContain(ev1.id);
    expect(pending.some((e: PhaseUpdateEvent) => e.eventType === 'phase_failed')).toBe(true);
  });

  it('markPhaseUpdateSent updates relayStatus', async () => {
    let ev = await appendPhaseUpdate({ eventType: 'phase_succeeded', phase: 'parse', summary: 'Parsed recipe' });
    let id = ev.id;
    let result = await markPhaseUpdateSent(id);
    expect(result).toBe(true);
    let pendingAfter = await getPendingPhaseUpdates();
    expect(pendingAfter.find((e: PhaseUpdateEvent) => e.id === id)).toBeUndefined();
    let all = await getAllPhaseUpdates();
    expect(all.find((e: PhaseUpdateEvent) => e.id === id)?.relayStatus).toBe('sent');
  });

  it('getAllPhaseUpdates reads back all events', async () => {
    await appendPhaseUpdate({ eventType: 'phase_started', phase: 'A', summary: 'Phase A started' });
    await appendPhaseUpdate({ eventType: 'phase_started', phase: 'B', summary: 'Phase B started' });
    const all = await getAllPhaseUpdates();
    expect(all.length).toBeGreaterThanOrEqual(2);
  });
});
