import type { ApiResponse } from "@/lib/api"
import type { ArticleListResult } from "@/lib/models/article"
import { callPublic } from "./base"

type RawArticleResponse = ArticleListResult | ArticleListResult[]

function normalizeListResult(
  result: RawArticleResponse | undefined,
): ArticleListResult {
  if (!result) return { RowCount: 0, List: [] }
  if (Array.isArray(result)) {
    return result[0] ?? { RowCount: 0, List: [] }
  }
  return result
}

export async function fetchArticles(
  props: { catalog?: number; keyword?: string } = {},
): Promise<ApiResponse<ArticleListResult>> {
  const params = new URLSearchParams()
  if (props.catalog !== undefined) params.set("Catalog", String(props.catalog))
  if (props.keyword?.trim()) params.set("KeyWord", props.keyword.trim())
  const query = params.toString()
  const res = await callPublic<RawArticleResponse>(
    `/article/apiindex${query ? `?${query}` : ""}`,
    undefined,
    "GET",
  )
  if (!res.success) return res
  return { success: true, data: normalizeListResult(res.data) }
}
