import { getLocale } from '$lib/paraglide/runtime'
import qs from 'qs'

const CMS_URL = import.meta.env.PUBLIC_CMS_URL ?? 'http://localhost:3000'

type FetchOptions = {
    locale?: string
    depth?: number
    where?: Record<string, unknown>
    select?: Record<string, boolean>
    limit?: number
    page?: number
    sort?: string
}

// Base fetch with locale + error handling
async function payloadFetch<T>(
    path: string,
    options: FetchOptions = {},
    fetchFn: typeof fetch = fetch
): Promise<T> {
    const locale = options.locale ?? getLocale()

    const query = qs.stringify(
        {
            locale,
            'fallback-locale': 'de',
            depth: options.depth ?? 1,
            ...(options.where && { where: options.where }),
            ...(options.select && { select: options.select }),
            ...(options.limit && { limit: options.limit }),
            ...(options.page && { page: options.page }),
            ...(options.sort && { sort: options.sort }),
        },
        { addQueryPrefix: true }
    )

    const res = await fetchFn(`${CMS_URL}/api${path}${query}`)

    if (!res.ok) {
        throw new Error(`Payload fetch failed: ${res.status} ${path}`)
    }

    return res.json()
}

// Collection — list
export async function getCollection<T>(
    slug: string,
    options: FetchOptions = {},
    fetchFn?: typeof fetch
) {
    return payloadFetch<{ docs: T[]; totalDocs: number; totalPages: number }>(
        `/${slug}`,
        options,
        fetchFn
    )
}

// Collection — single by slug
export async function getBySlug<T>(
    slug: string,
    value: string,
    options: FetchOptions = {},
    fetchFn?: typeof fetch
) {
    const data = await getCollection<T>(
        slug,
        {
            ...options,
            where: { slug: { equals: value } },
            limit: 1,
        },
        fetchFn
    )
    return data.docs[0] ?? null
}

// Global
export async function getGlobal<T>(
    slug: string,
    options: FetchOptions = {},
    fetchFn?: typeof fetch
) {
    return payloadFetch<T>(`/globals/${slug}`, options, fetchFn)
}