import { describe, expect, it } from 'vitest';
import { LIVE_QUERY_POLICY, QUERY_MEMORY, queryScopeKey, retainPreviousPageWithinScope } from './queryPolicy';

describe('query memory policy', () => {
  it('pauses live polling in hidden tabs and refreshes immediately on return', () => {
    expect(LIVE_QUERY_POLICY).toEqual({
      refetchIntervalInBackground: false,
      refetchOnWindowFocus: true
    });
  });
  it('drops high-volume route results immediately and bounds reusable small results', () => {
    expect(QUERY_MEMORY.highVolumeGcTime).toBe(0);
    expect(QUERY_MEMORY.optionGcTime).toBeLessThanOrEqual(30_000);
    expect(QUERY_MEMORY.summaryGcTime).toBeLessThanOrEqual(60_000);
  });

  it('retains placeholder rows only while paging inside the same query scope', () => {
    const previous = { rows: ['page-one'] };
    const placeholder = retainPreviousPageWithinScope<typeof previous>('vehicle=A&date=2026-07-16');

    expect(placeholder(previous, { queryKey: ['history-data', 'vehicle=A&date=2026-07-16', 50, 50] })).toBe(previous);
    expect(placeholder(previous, { queryKey: ['history-data', 'vehicle=B&date=2026-07-16', 50, 0] })).toBeUndefined();
    expect(placeholder(previous)).toBeUndefined();

    const nestedPlaceholder = retainPreviousPageWithinScope<typeof previous>('vehicle=A&date=2026-07-16', 2);
    expect(nestedPlaceholder(previous, { queryKey: ['monitor', 'workspace', 'vehicle=A&date=2026-07-16', 'viewport-b'] })).toBe(previous);
    expect(nestedPlaceholder(previous, { queryKey: ['monitor', 'workspace', 'vehicle=B&date=2026-07-16', 'viewport-b'] })).toBeUndefined();
  });

  it('builds a stable scope key independent of object order and empty values', () => {
    expect(queryScopeKey({ status: 'offline', keyword: '粤A 1', limit: undefined, protocol: '' }))
      .toBe(queryScopeKey({ protocol: '', keyword: '粤A 1', status: 'offline' }));
    expect(queryScopeKey({ status: 'offline', keyword: '粤A 1' })).toBe('keyword=%E7%B2%A4A%201&status=offline');
  });
});
