import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { MemoryDatastoreProvider } from '@bytelyst/datastore';
import { _resetDatastoreProvider, setProvider } from '../../lib/datastore.js';
import { clearRegistry, registerJob } from './registry.js';
import { executeJob } from './runner.js';
import * as runsRepo from '../runs/repository.js';
import type { JobDefinitionDoc } from './types.js';

describe('jobs runner', () => {
  beforeEach(() => {
    setProvider(new MemoryDatastoreProvider());
    clearRegistry();
  });

  afterEach(() => {
    clearRegistry();
    _resetDatastoreProvider();
  });

  it('writes a generic run record and step for executed jobs', async () => {
    registerJob('nightly-sync', async () => ({
      success: true,
      message: 'ok',
      metrics: { synced: 12 },
    }));

    const definition: JobDefinitionDoc = {
      id: 'job_nightly-sync',
      productId: 'lysnrai',
      name: 'nightly-sync',
      cronExpression: '0 * * * *',
      status: 'enabled',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      timeoutMs: 10_000,
      retryOnFailure: false,
      maxRetries: 0,
    };

    const log = {
      info: () => {},
      warn: () => {},
      error: () => {},
    };

    const run = await executeJob(definition, 'manual', log);
    const trackedRun = await runsRepo.getRun(run.id, 'lysnrai');
    const steps = await runsRepo.listRunSteps('lysnrai', run.id);

    expect(trackedRun.kind).toBe('job');
    expect(trackedRun.status).toBe('succeeded');
    expect(trackedRun.source).toBe('platform.jobs');
    expect(steps).toHaveLength(1);
    expect(steps[0]).toMatchObject({
      stepName: 'execute',
      status: 'succeeded',
    });
  });
});
