import type { NewsArticle } from '@/types'
import type { BackendNewsCategory } from '@/lib/backend'
import { publicAssetUrl, serverFetchJson } from '@/lib/server-api'

async function fetchJson<T>(path: string): Promise<T | null> {
  return serverFetchJson<T>(path)
}

function normalizeArticle<T extends NewsArticle>(article: T): T {
  return {
    ...article,
    coverUrl: publicAssetUrl(article.coverUrl),
    content: typeof article.content === 'string'
      ? article.content.replace(/src=(["'])\/api\//g, 'src=$1/api/')
      : article.content,
  }
}

export async function getNewsArticles(category = ''): Promise<NewsArticle[]> {
  const query = category ? `?category=${encodeURIComponent(category)}` : ''
  const data = await fetchJson<{ items: NewsArticle[] }>(`/news${query}`)
  return (data?.items || []).map(normalizeArticle)
}

export async function getFeaturedNewsArticles(): Promise<NewsArticle[]> {
  const data = await fetchJson<{ items: NewsArticle[] }>('/news/featured')
  return (data?.items || []).map(normalizeArticle)
}

export async function getNewsCategories(): Promise<BackendNewsCategory[]> {
  const data = await fetchJson<{ items: BackendNewsCategory[] }>('/news-categories')
  return data?.items || []
}

export async function getNewsArticle(slug: string): Promise<NewsArticle | null> {
  const article = await fetchJson<NewsArticle>(`/news/${encodeURIComponent(slug)}`)
  return article ? normalizeArticle(article) : null
}
