import { beforeEach, afterEach, describe, expect, it } from 'vitest';
import { MemoryDatastoreProvider } from '@bytelyst/datastore';
import { _resetDatastoreProvider, setProvider } from '../../lib/datastore.js';
import * as repo from './repository.js';

describe('runs repository', () => {
  beforeEach(() => {
    setProvider(new MemoryDatastoreProvider());
  });

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

  it('creates and retrieves runs with ordered steps', async () => {
    await repo.createRun({
      id: 'run_1',
      productId: 'lysnrai',
      kind: 'job',
      name: 'nightly-sync',
      source: 'platform.jobs',
      status: 'running',
      createdAt: '2026-03-14T00:00:00.000Z',
      startedAt: '2026-03-14T00:00:00.000Z',
      updatedAt: '2026-03-14T00:00:00.000Z',
    });

    await repo.createRunStep({
      id: 'run_1:collect',
      pk: 'lysnrai:run_1',
      runId: 'run_1',
      productId: 'lysnrai',
      stepName: 'collect',
      order: 2,
      status: 'running',
      createdAt: '2026-03-14T00:00:00.000Z',
      startedAt: '2026-03-14T00:00:00.000Z',
      updatedAt: '2026-03-14T00:00:00.000Z',
    });

    await repo.createRunStep({
      id: 'run_1:validate',
      pk: 'lysnrai:run_1',
      runId: 'run_1',
      productId: 'lysnrai',
      stepName: 'validate',
      order: 1,
      status: 'succeeded',
      createdAt: '2026-03-14T00:00:00.000Z',
      startedAt: '2026-03-14T00:00:00.000Z',
      completedAt: '2026-03-14T00:01:00.000Z',
      updatedAt: '2026-03-14T00:01:00.000Z',
    });

    const run = await repo.getRun('run_1', 'lysnrai');
    const steps = await repo.listRunSteps('lysnrai', 'run_1');

    expect(run.name).toBe('nightly-sync');
    expect(steps.map(step => step.stepName)).toEqual(['validate', 'collect']);
  });
});
