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

const callOrder: string[] = [];

const refreshAllCodexAccountUsage = vi.fn(async () => {
  callOrder.push('refreshAll');
  return { rows: [], fetchedAt: '2026-06-01T00:00:00.000Z' };
});
const refreshActiveCodexUsage = vi.fn(async () => {
  callOrder.push('refreshActive');
  return { rows: [], fetchedAt: '2026-06-01T00:00:01.000Z' };
});
const runCodexWarmupCycle = vi.fn(async () => {
  callOrder.push('warmup');
  return { status: 'warmed', accountIndex: 0 };
});

vi.mock('./config.js', () => ({
  CODEX_WARMUP_CONFIG: {
    enabled: false,
    prompt: 'Reply exactly OK. Do not run tools.',
    model: 'gpt-5.5',
    intervalMs: 300_000,
    minIntervalMs: 18_300_000,
    staggerMs: 1_800_000,
    maxUsagePct: 0,
    maxD7UsagePct: 0,
    commandTimeoutMs: 120_000,
    failureCooldownMs: 21_600_000,
    maxConsecutiveFailures: 2,
  },
}));

vi.mock('./logger.js', () => ({
  logger: {
    debug: vi.fn(),
    info: vi.fn(),
    warn: vi.fn(),
    error: vi.fn(),
  },
}));

vi.mock('./token-rotation.js', () => ({
  getAllTokens: vi.fn(() => []),
}));

vi.mock('./codex-usage-collector.js', () => ({
  refreshAllCodexAccountUsage,
  refreshActiveCodexUsage,
}));

vi.mock('./codex-warmup.js', () => ({
  runCodexWarmupCycle,
}));

describe('usage-primer', () => {
  it('fires the Codex primer first with forceAttempt and refreshes usage only afterwards', async () => {
    callOrder.length = 0;
    refreshAllCodexAccountUsage.mockClear();
    refreshActiveCodexUsage.mockClear();
    runCodexWarmupCycle.mockClear();

    const { runCodexPrimerCycle } = await import('./usage-primer.js');
    await runCodexPrimerCycle();

    // No pre-call usage refresh (that was the off-slot latency source); the
    // command fires immediately, then usage is refreshed for observability.
    expect(callOrder).toEqual(['warmup', 'refreshActive']);
    expect(refreshAllCodexAccountUsage).not.toHaveBeenCalled();
    expect(runCodexWarmupCycle).toHaveBeenCalledWith(
      expect.objectContaining({
        enabled: true,
        minIntervalMs: 18_000_000,
        maxUsagePct: 100,
        maxD7UsagePct: 100,
      }),
      { ignoreZeroUsageWindow: true, forceAttempt: true },
    );
  });
});
