import { DIRECTUS_URL } from './env'

export type DirectusListResponse<T> = {
  data: T[]
  meta?: { filter_count?: number; total_count?: number }
}

export type DirectusItemResponse<T> = {
  data: T
}

export type DirectusFilter = Record<string, unknown>

export type DirectusQuery = {
  fields?: string[]
  filter?: DirectusFilter
  sort?: string
  limit?: number
  page?: number
  meta?: string[]
}

function buildUrl(collection: string, q: DirectusQuery = {}): string {
  const url = new URL(`${DIRECTUS_URL}/items/${collection}`)
  for (const field of q.fields ?? []) url.searchParams.append('fields[]', field)
  for (const m of q.meta ?? []) url.searchParams.append('meta[]', m)
  if (q.filter) url.searchParams.append('filter', JSON.stringify(q.filter))
  if (q.sort) url.searchParams.append('sort', q.sort)
  if (q.limit !== undefined) url.searchParams.append('limit', String(q.limit))
  if (q.page !== undefined) url.searchParams.append('page', String(q.page))
  return url.toString()
}

export async function directusList<T>(
  collection: string,
  q: DirectusQuery = {},
): Promise<DirectusListResponse<T>> {
  const res = await fetch(buildUrl(collection, q))
  if (!res.ok) throw new Error(`Directus error ${res.status} on /items/${collection}`)
  return (await res.json()) as DirectusListResponse<T>
}

export async function directusOne<T>(collection: string, q: DirectusQuery = {}): Promise<T | undefined> {
  const { data } = await directusList<T>(collection, { ...q, limit: 1 })
  return data[0]
}

export async function directusSingleton<T>(collection: string, q: DirectusQuery = {}): Promise<T> {
  const url = new URL(`${DIRECTUS_URL}/items/${collection}`)
  for (const field of q.fields ?? []) url.searchParams.append('fields[]', field)
  const res = await fetch(url.toString())
  if (!res.ok) throw new Error(`Directus error ${res.status} on /items/${collection}`)
  const { data } = (await res.json()) as DirectusItemResponse<T>
  return data
}

export function assetUrl(fileId: string | null | undefined, key?: string): string {
  if (!fileId) return ''
  const url = new URL(`${DIRECTUS_URL}/assets/${fileId}`)
  if (key) url.searchParams.append('key', key)
  return url.toString()
}
