import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { get, postForm } from '@/utils/request'
import type { Announcement } from '@/types'

interface AnnouncementApiItem {
  id: string
  title: string
  content: string
  createTime: string
  imgUrl?: string
  isTop?: string
  lang?: string
  sort?: number
  announcementClassification?: number
}

interface AnnouncementPageResp {
  content: AnnouncementApiItem[]
  totalElements: number
}

function mapItem(r: AnnouncementApiItem): Announcement {
  return {
    id: r.id,
    title: r.title ?? '',
    content: r.content ?? '',
    publishedAt: r.createTime ?? '',
    author: 'iBit 官方团队',
  }
}

export const useAnnouncementsStore = defineStore('announcements', () => {
  // ── State ──────────────────────────────────────────
  const list = ref<Announcement[]>([])
  const current = ref<Announcement | null>(null)
  const loading = ref(false)
  const detailLoading = ref(false)
  const error = ref('')

  const pageNo = ref(1)
  const pageSize = ref(15)
  const total = ref(0)

  // ── Getters ────────────────────────────────────────
  const recentList = computed(() => list.value.slice(0, 5))
  const hasMore = computed(() => list.value.length < total.value)

  // ── Actions ────────────────────────────────────────
  async function fetchList(page = 1) {
    loading.value = true
    error.value = ''
    try {
      const res = await postForm<AnnouncementPageResp>('uc/announcement/page', {
        pageNo: page,
        pageSize: pageSize.value,
      })
      const items = Array.isArray(res?.content) ? res.content.map(mapItem) : []
      if (page === 1) {
        list.value = items
      } else {
        list.value = [...list.value, ...items]
      }
      pageNo.value = page
      total.value = res?.totalElements ?? items.length
    } catch (e) {
      error.value = e instanceof Error ? e.message : '获取公告失败'
      if (page === 1) list.value = []
    } finally {
      loading.value = false
    }
  }

  async function loadMore() {
    if (loading.value || !hasMore.value) return
    await fetchList(pageNo.value + 1)
  }

  async function fetchById(id: string | number) {
    detailLoading.value = true
    current.value = null
    error.value = ''
    try {
      const res = await get<AnnouncementApiItem>(`uc/announcement/${id}`)
      if (res && typeof res === 'object') {
        current.value = mapItem(res as AnnouncementApiItem)
      }
    } catch (e) {
      error.value = e instanceof Error ? e.message : '获取公告详情失败'
    } finally {
      detailLoading.value = false
    }
  }

  return {
    list,
    current,
    loading,
    detailLoading,
    error,
    pageNo,
    pageSize,
    total,
    recentList,
    hasMore,
    fetchList,
    loadMore,
    fetchById,
  }
})
