import { getCookie } from 'cookies-next'

// URL de base : tout passe par le proxy Next.js (cookies httpOnly-friendly,
// pas de CORS direct vers le backend AdonisJS).
export const API_URL = '/api/proxy'

export class ApiError extends Error {
  status: number
  data: unknown
  response: { status: number; data: unknown }

  constructor(message: string, status: number, data: unknown) {
    super(message)
    this.name = 'ApiError'
    this.status = status
    this.data = data
    this.response = { status, data }
  }
}

type ApiErrorPayload = {
  message?: string
  error?: string
  errors?: Array<{ message?: string } | string>
}

const isErrorPayload = (payload: unknown): payload is ApiErrorPayload =>
  typeof payload === 'object' && payload !== null

export const extractErrorMessage = (payload: unknown, fallback: string): string => {
  if (!isErrorPayload(payload)) return fallback

  if (typeof payload.message === 'string' && payload.message.trim().length > 0) {
    return payload.message
  }
  if (typeof payload.error === 'string' && payload.error.trim().length > 0) {
    return payload.error
  }
  if (Array.isArray(payload.errors) && payload.errors.length > 0) {
    const first = payload.errors[0]
    if (typeof first === 'string') return first
    if (first && typeof first === 'object' && typeof first.message === 'string') return first.message
  }

  return fallback
}

// Traductions FR pour les messages de validation les plus courants côté users.
export const translateErrorMessage = (message: string): string => {
  const normalized = message.toLowerCase().trim()

  if (normalized.includes('email has already been taken') || normalized.includes('email already exists')) {
    return 'Cet email est déjà utilisé'
  }
  if (normalized.includes('phone has already been taken') || normalized.includes('phone already exists')) {
    return 'Ce numéro de téléphone est déjà utilisé'
  }
  if (normalized.includes('validation failed') || normalized.includes('validation error')) {
    return 'Les informations fournies sont invalides'
  }

  return message
}

export const hasData = <T>(payload: unknown): payload is { data: T } =>
  typeof payload === 'object' && payload !== null && 'data' in payload

/**
 * Certains endpoints répondent 200 avec `{ message: "..." }` sans `data` en
 * cas d'échec métier (au lieu d'un vrai code d'erreur HTTP). apiFetch ne le
 * détecte pas (response.ok est true) : les appelants concernés doivent
 * appeler ce garde juste après pour transformer ce cas en erreur exploitable.
 */
export function assertNoErrorMessage(payload: unknown): void {
  const obj = payload as { data?: unknown; message?: string } | null | undefined
  if (obj && obj.message && obj.data === undefined) {
    throw new ApiError(obj.message, 200, obj)
  }
}

type QueryValue = string | number | boolean | undefined | null

export type ApiFetchOptions = Omit<RequestInit, 'body'> & {
  /** Objet JS auto-sérialisé en JSON, FormData (multipart), ou string déjà sérialisée. */
  body?: BodyInit | object | null
  /** Paramètres de query string ; les valeurs undefined/null/'' sont omises. */
  params?: Record<string, QueryValue>
}

function buildQueryString(params?: Record<string, QueryValue>): string {
  if (!params) return ''
  const search = new URLSearchParams()
  for (const [key, value] of Object.entries(params)) {
    if (value !== undefined && value !== null && value !== '') {
      search.append(key, String(value))
    }
  }
  const qs = search.toString()
  return qs ? `?${qs}` : ''
}

/**
 * Client HTTP unique pour l'admin, remplace la logique (headers, token,
 * parsing JSON, gestion d'erreur) auparavant dupliquée dans chaque fichier
 * de src/lib. Toutes les requêtes passent par /api/proxy.
 */
export async function apiFetch<T = unknown>(path: string, options: ApiFetchOptions = {}): Promise<T> {
  const { params, body, headers, ...rest } = options
  const token = getCookie('authToken')

  const isFormData = typeof FormData !== 'undefined' && body instanceof FormData
  const isPlainObjectBody = body !== undefined && body !== null && !isFormData && typeof body !== 'string'

  const finalHeaders: HeadersInit = {
    Accept: 'application/json',
    ...(isFormData ? {} : { 'Content-Type': 'application/json' }),
    ...(typeof token === 'string' ? { Authorization: `Bearer ${token}` } : {}),
    ...headers,
  }

  const response = await fetch(`${API_URL}${path}${buildQueryString(params)}`, {
    ...rest,
    headers: finalHeaders,
    body: isPlainObjectBody ? JSON.stringify(body) : (body as BodyInit | null | undefined),
    credentials: 'include',
  })

  let payload: unknown = null
  try {
    payload = await response.json()
  } catch {
    payload = null
  }

  if (!response.ok) {
    throw new ApiError(extractErrorMessage(payload, `Erreur HTTP ${response.status}`), response.status, payload)
  }

  return payload as T
}
