const API_URL = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost/api"

export const apiFetch = async (endpoint: string, options: RequestInit = {}) => {
  const token = typeof window !== "undefined" ? localStorage.getItem("token") : null

  const headers = {
    "Content-Type": "application/json",
    Accept: "application/json",
    ...options.headers,
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  }

  try {
    const response = await fetch(`${API_URL}${endpoint}`, {
      ...options,
      headers,
      cache: "no-store",
    })

    if (response.status === 401) {
      if (typeof window !== "undefined") localStorage.removeItem("token")
    }

    // If backend is having issues (500+), return a mock response for fallback
    if (response.status >= 500) {
      return new Response(null, { status: 503, statusText: "Backend unavailable" })
    }

    return response
  } catch (error) {
    return new Response(null, { status: 503, statusText: "Network error" })
  }
}

export const getErrorMessage = async (response: Response): Promise<string> => {
  try {
    const contentType = response.headers.get("content-type")
    if (contentType && contentType.indexOf("application/json") !== -1) {
      const data = await response.json()

      // Laravel Validation Errors
      if (data.errors) {
        // flatten errors
        const messages = Object.values(data.errors).flat()
        if (messages.length > 0) return messages[0] as string // Return first error
      }

      // Explicit message
      if (data.message) return data.message
    }

    return response.statusText ? `Error ${response.status}: ${response.statusText}` : `Error desconocido (${response.status})`
  } catch (e) {
    return "Error al procesar la respuesta del servidor"
  }
}
