import { describe, expect, it, vi } from 'vitest'
import type { LocationQuery } from 'vue-router'
import {
  clearStoredHomeQuery,
  decodeHomeQueryJson,
  encodeHomeQueryJson,
  hasHomeQueryValues,
  isSameQuery,
  mergeHomeQuery,
  readStoredHomeQuery,
  joinQueryCSV,
  readQueryCSV,
  readQueryNumber,
  readQueryString,
  storeHomeQuery,
} from '@/features/listings/composables/useHomeFilterQuery'

describe('useHomeFilterQuery', () => {
  it('应该从路由 query 中读取字符串和数字', () => {
    const query: LocationQuery = {
      keyword: ['测试账号'],
      min_coin: '100',
      max_coin: 'abc',
    }

    expect(readQueryString(query, 'keyword')).toBe('测试账号')
    expect(readQueryNumber(query, 'min_coin')).toBe(100)
    expect(readQueryNumber(query, 'max_coin')).toBeUndefined()
  })

  it('应该读写 CSV 多选筛选参数', () => {
    expect(readQueryCSV({ insurance: '3*3,2*2,3*3' }, 'insurance')).toEqual(['3*3', '2*2'])
    expect(readQueryCSV({ insurance: '3*3' }, 'insurance')).toEqual(['3*3'])
    expect(readQueryCSV({}, 'insurance')).toEqual([])
    expect(joinQueryCSV(['3*3', '2*2', '3*3'])).toBe('3*3,2*2')
    expect(joinQueryCSV([])).toBeUndefined()
  })

  it('应该合并新筛选并移除旧的托管参数', () => {
    const query = mergeHomeQuery(
      { keyword: '旧关键词', page: '2', region: '上海' },
      ['keyword', 'region', 'sort'],
      { keyword: '新关键词', sort: undefined }
    )

    expect(query).toEqual({
      page: '2',
      keyword: '新关键词',
    })
  })

  it('应该判断 query 是否语义一致', () => {
    expect(isSameQuery({ keyword: '测试', empty: '' }, { empty: undefined, keyword: '测试' })).toBe(
      true
    )
  })

  it('应该安全编码和恢复移动端动态筛选', () => {
    const filters = { server: ['微信区'], operatorRed: ['红皮肤'] }
    const encoded = encodeHomeQueryJson(filters)

    expect(encoded).toBe(JSON.stringify(filters))
    expect(decodeHomeQueryJson({ filters: encoded }, 'filters', {})).toEqual(filters)
    expect(decodeHomeQueryJson({ filters: '{' }, 'filters', { server: [] })).toEqual({
      server: [],
    })
  })

  it('应该判断并缓存首页筛选参数', () => {
    const storage = new Map<string, string>()
    vi.stubGlobal('window', {
      sessionStorage: {
        getItem: (key: string) => storage.get(key) ?? null,
        setItem: (key: string, value: string) => storage.set(key, value),
        removeItem: (key: string) => storage.delete(key),
      },
    })
    const storageKey = 'hfb.home.filters.test'
    const query = { keyword: '测试', zone: 'gift' }

    try {
      expect(hasHomeQueryValues(query, ['keyword', 'zone'])).toBe(true)
      storeHomeQuery(storageKey, query)
      expect(readStoredHomeQuery(storageKey)).toEqual(query)
      clearStoredHomeQuery(storageKey)
      expect(readStoredHomeQuery(storageKey)).toEqual({})
    } finally {
      vi.unstubAllGlobals()
    }
  })
})
