import { BackgroundJobWorker } from './background-job.worker';

describe('BackgroundJobWorker', () => {
  it('runs a registered handler and marks the job succeeded', async () => {
    const lock = {
      claimNext: jest.fn().mockResolvedValue({
        id: 'job-1',
        type: 'demo.job',
        payload: { ok: true },
      }),
    };
    const jobs = {
      markSucceeded: jest.fn(),
      markFailed: jest.fn(),
    };
    const worker = new BackgroundJobWorker(lock as any, jobs as any);
    const handler = jest.fn().mockResolvedValue(undefined);
    worker.registerHandler('demo.job', handler);

    await expect(worker.runOnce({ workerId: 'worker-a' })).resolves.toBe(true);

    expect(handler).toHaveBeenCalledWith({ ok: true }, expect.objectContaining({ id: 'job-1' }));
    expect(jobs.markSucceeded).toHaveBeenCalledWith('job-1');
    expect(jobs.markFailed).not.toHaveBeenCalled();
  });

  it('marks a job failed when the handler throws', async () => {
    const lock = {
      claimNext: jest.fn().mockResolvedValue({
        id: 'job-1',
        type: 'demo.job',
        payload: {},
      }),
    };
    const jobs = {
      markSucceeded: jest.fn(),
      markFailed: jest.fn(),
    };
    const worker = new BackgroundJobWorker(lock as any, jobs as any);
    const error = new Error('bad handler');
    worker.registerHandler('demo.job', jest.fn().mockRejectedValue(error));

    await expect(worker.runOnce({ workerId: 'worker-a' })).resolves.toBe(false);

    expect(jobs.markFailed).toHaveBeenCalledWith('job-1', error, expect.any(Object));
    expect(jobs.markSucceeded).not.toHaveBeenCalled();
  });
});
