import type { WikiPage, WikiPageWithContent, WikiPageContent } from '../lib/interfaces/wiki.interface'

import { CONFIG } from '../lib/config'

// Public content base — used only for building external links to wiki pages.
const WIKI_BASE = CONFIG.wikiBase

interface RawWikiPage {
  id: number
  path: string
  title?: string
  description?: string
  content?: string
  render?: string
  updatedAt: string
  createdAt: string
  locale: string
  repo?: string | null
}

async function fetchPages(
  tag: string,
  opts: { body?: boolean; limit?: number } = {},
): Promise<RawWikiPage[]> {
  const params = new URLSearchParams({ tag })
  if (opts.body) params.set('body', '1')
  if (opts.limit) params.set('limit', String(opts.limit))

  const res = await fetch(`/api/wiki/pages?${params.toString()}`)
  if (!res.ok) throw new Error(`Wiki API error: ${res.status}`)
  const json = await res.json()
  return json?.pages ?? []
}

const listBlogPages = async (): Promise<WikiPageWithContent[]> => {
  const pages = await fetchPages('blog', { body: true })
  return pages.map((p): WikiPageWithContent => ({
    id: p.id,
    path: p.path,
    title: p.title || p.path,
    description: p.description ?? '',
    content: p.content ?? '',
    updatedAt: p.updatedAt,
    createdAt: p.createdAt,
    locale: p.locale,
  }))
}

const getBlogPage = async (slug: string): Promise<WikiPageContent | null> => {
  const pages = await fetchPages('blog', { body: true })

  const matched = pages.find((p) => {
    const pageSlug = p.path.startsWith('blog/') ? p.path.replace('blog/', '') : p.path
    return pageSlug === slug
  })

  if (!matched) return null

  return {
    id: matched.id,
    path: matched.path,
    title: matched.title || matched.path,
    description: matched.description ?? '',
    render: matched.render ?? '',
    updatedAt: matched.updatedAt,
    createdAt: matched.createdAt,
    locale: matched.locale,
  }
}

const listEnginePages = async (): Promise<WikiPageWithContent[]> => {
  const pages = await fetchPages('engine', { body: true })
  return pages.map((p): WikiPageWithContent => ({
    id: p.id,
    path: p.path,
    title: p.title || p.path,
    description: p.description ?? '',
    content: p.content ?? '',
    updatedAt: p.updatedAt,
    createdAt: p.createdAt,
    locale: p.locale,
    repo: p.repo ?? null,
  }))
}

const listHowtoPages = async (): Promise<WikiPage[]> => {
  const pages = await fetchPages('howto', { limit: 30 })
  return pages.map((p): WikiPage => ({
    id: p.id,
    path: p.path,
    title: p.title || p.path,
    description: p.description ?? '',
    updatedAt: p.updatedAt,
    createdAt: p.createdAt,
    locale: p.locale,
  }))
}

export { WIKI_BASE }
export default { listBlogPages, getBlogPage, listHowtoPages, listEnginePages }
