import { describe, it, expect, vi, afterEach } from 'vitest';
import { fetchFileProvenance } from './api';

afterEach(() => { vi.restoreAllMocks(); });

describe('fetchFileProvenance', () => {
  it('requests the provenance endpoint with section + path and returns the record', async () => {
    const record = { relPath: 'output/a.md', sourceKind: 'agent_output', createdByTaskId: 7 };
    const spy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
      new Response(JSON.stringify({ provenance: record }), { status: 200 }),
    );
    const out = await fetchFileProvenance(1, 'output', 'a.md');
    expect(out).toEqual(record);
    const url = String(spy.mock.calls[0]![0]);
    expect(url).toContain('/api/local/tasks/1/files/provenance?');
    expect(url).toContain('section=output');
    expect(url).toContain('path=a.md');
  });

  it('returns null on a non-ok response instead of throwing', async () => {
    vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response('nope', { status: 500 }));
    await expect(fetchFileProvenance(1, 'output', 'a.md')).resolves.toBeNull();
  });

  it('returns null when the record is absent', async () => {
    vi.spyOn(globalThis, 'fetch').mockResolvedValue(
      new Response(JSON.stringify({ provenance: null }), { status: 200 }),
    );
    await expect(fetchFileProvenance(1, 'output', 'ghost.md')).resolves.toBeNull();
  });
});
