import { describe, it, expect, beforeEach, vi } from 'vitest'
import { createPinia, setActivePinia } from 'pinia'
import { useDictionaryOverrideStore } from '@/store/modules/dictionaryOverride'

vi.mock('element-plus', () => ({
  ElMessage: {
    error: vi.fn(),
    success: vi.fn()
  }
}))

const getOverridesMock = vi.fn()
const getOverrideMock = vi.fn()
const enableOverrideMock = vi.fn()
const disableOverrideMock = vi.fn()
const updateHiddenItemsMock = vi.fn()
const updateSortOrderMock = vi.fn()

vi.mock('@/api/dictionary/override', () => ({
  getOverrides: (...args: unknown[]) => getOverridesMock(...args),
  getOverride: (...args: unknown[]) => getOverrideMock(...args),
  enableOverride: (...args: unknown[]) => enableOverrideMock(...args),
  disableOverride: (...args: unknown[]) => disableOverrideMock(...args),
  updateHiddenItems: (...args: unknown[]) => updateHiddenItemsMock(...args),
  updateSortOrder: (...args: unknown[]) => updateSortOrderMock(...args)
}))

describe('dictionaryOverride store', () => {
  beforeEach(() => {
    setActivePinia(createPinia())
    vi.clearAllMocks()
  })

  it('enableOverride calls API and updates state', async () => {
    const store = useDictionaryOverrideStore()
    const config: Api.Dictionary.OverrideConfigDto = {
      tenantId: '100',
      systemDictionaryGroupCode: 'ORDER_STATUS',
      overrideEnabled: true,
      hiddenSystemItemIds: [],
      customSortOrder: {}
    }
    enableOverrideMock.mockResolvedValue(config)

    const result = await store.enableOverride('ORDER_STATUS')

    expect(result).toEqual(config)
    expect(store.overrides['order_status']).toEqual(config)
  })

  it('updateHiddenItems updates config', async () => {
    const store = useDictionaryOverrideStore()
    const config: Api.Dictionary.OverrideConfigDto = {
      tenantId: '100',
      systemDictionaryGroupCode: 'PAYMENT_METHOD',
      overrideEnabled: true,
      hiddenSystemItemIds: ['1', '2'],
      customSortOrder: {}
    }
    updateHiddenItemsMock.mockResolvedValue(config)

    const result = await store.updateHiddenItems('PAYMENT_METHOD', ['1', '2'])

    expect(result).toEqual(config)
    expect(store.overrides.payment_method).toEqual(config)
  })

  it('clearCache invalidates all cached overrides', async () => {
    const store = useDictionaryOverrideStore()
    const configs: Api.Dictionary.OverrideConfigDto[] = [
      {
        tenantId: '100',
        systemDictionaryGroupCode: 'ORDER_STATUS',
        overrideEnabled: true,
        hiddenSystemItemIds: [],
        customSortOrder: {}
      }
    ]
    getOverridesMock.mockResolvedValue(configs)

    await store.clearCache()

    expect(getOverridesMock).toHaveBeenCalled()
    expect(store.overrides['order_status']).toEqual(configs[0])
  })
})
