import { describe, expect, it, vi } from 'vitest';

import { createBatchIdCandidate, createUniqueBatchId } from '@/lib/batchId';

describe('batchId', () => {
  it('builds a CG-YYYYMMDD-NNN batch id', () => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2026-04-08T09:07:00.000Z'));

    const batchId = createBatchIdCandidate(1);

    expect(batchId).toBe('CG-20260408-001');

    vi.useRealTimers();
  });

  it('increments sequence for subsequent calls', () => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2026-04-08T09:07:00.000Z'));

    const first = createBatchIdCandidate(1);
    const second = createBatchIdCandidate(2);

    expect(first).toBe('CG-20260408-001');
    expect(second).toBe('CG-20260408-002');

    vi.useRealTimers();
  });

  it('retries until it finds a unique batch id', async () => {
    const exists = vi
      .fn<(_: string) => Promise<boolean>>()
      .mockResolvedValueOnce(true)
      .mockResolvedValueOnce(false);

    const batchId = await createUniqueBatchId(exists, 2);

    expect(batchId).toMatch(/^CG-/);
    expect(exists).toHaveBeenCalledTimes(2);
  });
});