import { api } from '@/utils/request'
import type {
  PaginatedData,
  FailedMessageRecord,
  FailedMessageFilters,
} from '@/types/api'

export type { FailedMessageRecord }

interface LookupItem {
  id: number
  name: string
  label?: string
}

export const useFailedMessageStore = defineStore('failedMessage', () => {
  const messages = ref<FailedMessageRecord[]>([])
  const loading = ref(false)
  const pagination = reactive({
    page: 1,
    per_page: 15,
    total: 0,
  })
  const filters = reactive<FailedMessageFilters>({
    data_type: undefined,
    platform_id: undefined,
    failed_at_range: null,
  })

  const platforms = ref<LookupItem[]>([])
  const platformMap = computed(
    () => new Map(platforms.value.map((p) => [p.id, p.label || p.name || `平台 #${p.id}`])),
  )

  async function loadLookups() {
    try {
      const p = await api.get<LookupItem[]>('/api/v1/platforms')
      platforms.value = p
    } catch (err: unknown) {
      console.warn('加载平台列表失败', err)
    }
  }

  async function fetchMessages() {
    loading.value = true
    try {
      const data = await api.get<PaginatedData<FailedMessageRecord>>('/api/v1/failed-messages', {
        page: pagination.page,
        per_page: pagination.per_page,
        data_type: filters.data_type || undefined,
        platform_id: filters.platform_id || undefined,
        failed_at_from: filters.failed_at_range?.[0] || undefined,
        failed_at_to: filters.failed_at_range?.[1] || undefined,
      })
      messages.value = data.items
      pagination.total = data.total
      pagination.page = data.page
    } catch (err: unknown) {
      messages.value = []
      pagination.total = 0
      const msg = err instanceof Error ? err.message : '获取失败消息列表失败'
      message.error(msg)
    } finally {
      loading.value = false
    }
  }

  function resetFilters() {
    filters.data_type = undefined
    filters.platform_id = undefined
    filters.failed_at_range = null
    pagination.page = 1
  }

  return {
    messages,
    loading,
    pagination,
    filters,
    platforms,
    platformMap,
    loadLookups,
    fetchMessages,
    resetFilters,
  }
})
