import { describe, expect, it } from 'vitest'
import { decodeCrudQuery, encodeCrudQuery } from '../queryCodec'
const fallback = { page: 1, pageSize: 20, sorts: [], filters: [] }
describe('CRUD URL codec', () => {
  it('round-trips paging, sort, filter and search without hidden Pinia state', () => {
    const source = { page: 3, pageSize: 50, search: '005930', sorts: [{ field: 'asOf', direction: 'desc' as const }], filters: [{ field: 'status', operator: 'eq', value: 'WARN' }] }
    expect(decodeCrudQuery(encodeCrudQuery(source), fallback)).toEqual(source)
  })
  it('fails closed to approved defaults for invalid paging', () => {
    expect(decodeCrudQuery(new URLSearchParams('page=0&pageSize=-1'), fallback)).toEqual({ ...fallback, search: undefined })
  })

  it('drops unapproved sort fields, filter fields, and operators when a whitelist is supplied', () => {
    const params = new URLSearchParams('sort=secret:desc&sort=asOf:asc&filter=secret:eq:x&filter=status:contains:READY&filter=status:eq:READY')
    expect(decodeCrudQuery(params, fallback, {
      allowedSortFields: new Set(['asOf']),
      allowedFilterFields: new Set(['status']),
      allowedFilterOperators: new Set(['eq'])
    })).toEqual({
      ...fallback,
      sorts: [{ field: 'asOf', direction: 'asc' }],
      filters: [{ field: 'status', operator: 'eq', value: 'READY' }],
      search: undefined
    })
  })
})
