import axios from "axios";
import { getStoredLocale } from "@/lib/getLocale";
import { getLocation, getSavedLocation } from "../utils/location";

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL;

export async function getProductById(id: string) {
  try {
    const locale = getStoredLocale();
    const response = await axios.get(`${API_BASE_URL}/products/${id}`, {
      headers: {
        "Content-Type": "application/json",
        "Accept-Language": locale,
      },
    });

    if (response.data.success) {
      return { data: response.data.data, error: null };
    }

    return {
      data: null,
      error: response.data.message || "Failed to fetch product",
    };
  } catch (error: any) {
    return {
      data: null,
      error:
        error.response?.data?.message ||
        "Failed to fetch product. Please try again later.",
    };
  }
}

export const getProductDetails = async (productId: string, token?: string) => {
  try {
    let url = `${process.env.NEXT_PUBLIC_API_URL}/home/product/${productId}/view`;
    const location = getSavedLocation();
    if (location) {
      url += `?latitude=${location.lat}&longitude=${location.lng}`;
    }
    const locale = getStoredLocale();
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      "Accept-Language": locale,
    };

    if (token) {
      headers["Authorization"] = `Bearer ${token}`;
    }

    const response = await axios.get(url, { headers });
    return response.data;
  } catch (error: any) {
    return {
      error: error.response?.data?.message || "Failed to fetch product details",
    };
  }
};
