export const API_BASE_URL = import.meta.env.VITE_API_URL || "http://localhost:5000"

export function formatRupiah(value) {
  return new Intl.NumberFormat("id-ID", {
    style: "currency",
    currency: "IDR",
    maximumFractionDigits: 0
  }).format(value)
}

export function getLocal(key, fallback) {
  try {
    const value = localStorage.getItem(key)
    return value ? JSON.parse(value) : fallback
  } catch {
    return fallback
  }
}

export function setLocal(key, value) {
  localStorage.setItem(key, JSON.stringify(value))
}

export function getToken() {
  return localStorage.getItem("secondtech_token")
}

export function getCurrentUser() {
  return getLocal("secondtech_user", null)
}

export function setAuth({ token, user }) {
  localStorage.setItem("secondtech_token", token)

  setLocal("secondtech_user", {
    id: user.id,
    name: user.name,
    email: user.email,
    whatsapp: user.whatsapp,
    role: user.role || "user"
  })
}

export function clearAuth() {
  localStorage.removeItem("secondtech_token")
  localStorage.removeItem("secondtech_user")
}

export function getProductImageUrl(image) {
  if (!image) return ""
  if (image.startsWith("http://") || image.startsWith("https://") || image.startsWith("data:")) return image
  return `${API_BASE_URL}${image}`
}

async function requestJson(path, options = {}) {
  const headers = new Headers(options.headers || {})
  const token = getToken()

  if (token) headers.set("Authorization", `Bearer ${token}`)
  if (!(options.body instanceof FormData)) headers.set("Content-Type", "application/json")

  const response = await fetch(`${API_BASE_URL}${path}`, {
    ...options,
    headers
  })
  const data = await response.json().catch(() => ({}))

  if (!response.ok) {
    throw new Error(data.message || "Request gagal.")
  }

  return data
}

export function registerUser(payload) {
  return requestJson("/api/auth/register", {
    method: "POST",
    body: JSON.stringify(payload)
  })
}

export function loginUser(payload) {
  return requestJson("/api/auth/login", {
    method: "POST",
    body: JSON.stringify(payload)
  })
}

export function fetchCurrentUser() {
  return requestJson("/api/auth/me")
}

export function fetchProducts() {
  return requestJson("/api/products")
}

export function fetchProduct(id) {
  return requestJson(`/api/products/${id}`)
}

export function fetchMyProducts() {
  return requestJson("/api/products/mine")
}

export function createProduct(formData) {
  return requestJson("/api/products", {
    method: "POST",
    body: formData
  })
}

export function updateProduct(id, formData) {
  return requestJson(`/api/products/${id}`, {
    method: "PUT",
    body: formData
  })
}

export function updateProductStatus(id, status) {
  return requestJson(`/api/products/${id}/status`, {
    method: "PATCH",
    body: JSON.stringify({ status })
  })
}

export function deleteProductById(id) {
  return requestJson(`/api/products/${id}`, {
    method: "DELETE"
  })
}

export function deleteProductAsAdmin(id) {
  return requestJson(`/api/admin/products/${id}`, {
    method: "DELETE"
  })
}

export function getSavedProducts() {
  return getLocal("secondtech_saved", [])
}

export function setSavedProducts(ids) {
  setLocal("secondtech_saved", ids)
}
