const API_BASE =
  (typeof window === 'undefined' ? process.env.API_INTERNAL_URL : process.env.NEXT_PUBLIC_API_URL)
  ?? process.env.NEXT_PUBLIC_API_URL
  ?? 'http://localhost:4000/api/v1'
export const DEFAULT_COMPANY_SLUG = process.env.NEXT_PUBLIC_COMPANY_SLUG ?? 'demo'

export class SiteApiError extends Error {
  status: number
  code?: string

  constructor(message: string, status: number, code?: string) {
    super(message)
    this.name = 'SiteApiError'
    this.status = status
    this.code = code
  }
}

export async function siteFetch<T>(path: string): Promise<T> {
  const res = await fetch(`${API_BASE}${path}`, { cache: 'no-store' })
  const json = await res.json().catch(() => null)
  if (!res.ok) throw new SiteApiError(json?.message ?? 'Request failed', res.status, json?.error)
  return json.data as T
}

export async function siteFetchOrDefault<T>(path: string, fallback: T): Promise<T> {
  try {
    return await siteFetch<T>(path)
  } catch {
    return fallback
  }
}
