import {
  clearOpsRuntimeEventsForTests,
  getOpsRuntimeEvents,
  recordSlowPrismaQuery,
  recordSlowRequest,
} from './ops-runtime.store';

describe('ops runtime store', () => {
  afterEach(() => clearOpsRuntimeEventsForTests());

  it('records recent slow requests without leaking query-string secrets', () => {
    recordSlowRequest({
      method: 'GET',
      url: '/api/v1/config/ai?apiKey=sk-secret&visible=1',
      durationMs: 1300,
      thresholdMs: 1000,
      occurredAt: new Date('2026-07-08T08:00:00.000Z'),
    });

    const events = getOpsRuntimeEvents();

    expect(events.slowRequests).toEqual([
      expect.objectContaining({
        method: 'GET',
        path: '/api/v1/config/ai',
        durationMs: 1300,
        thresholdMs: 1000,
        occurredAt: '2026-07-08T08:00:00.000Z',
      }),
    ]);
    expect(JSON.stringify(events)).not.toContain('sk-secret');
  });

  it('records recent slow Prisma queries with redacted and bounded previews', () => {
    recordSlowPrismaQuery({
      query: `SELECT * FROM ai_logs WHERE metadata::text LIKE '%sk-secret-token%' ${'x'.repeat(400)}`,
      durationMs: 450,
      thresholdMs: 300,
      occurredAt: new Date('2026-07-08T08:01:00.000Z'),
    });

    const [event] = getOpsRuntimeEvents().slowQueries;

    expect(event).toEqual(expect.objectContaining({
      durationMs: 450,
      thresholdMs: 300,
      occurredAt: '2026-07-08T08:01:00.000Z',
    }));
    expect(event.queryPreview).toContain('[redacted]');
    expect(event.queryPreview.length).toBeLessThanOrEqual(240);
    expect(event.queryPreview).not.toContain('sk-secret-token');
  });
});
