import axios from "axios";
import { getLocation, getSavedLocation } from "../utils/location";

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3011";

export async function storeRecentlyViewedProduct(
  productId: string,
  token: string,
  locale: string,
): Promise<boolean> {
  if (!token) return false;
  try {
    const response = await axios.post(
      `${API_BASE_URL}/products/recently-viewed/store`,
      { productId },
      {
        withCredentials: true,
        headers: {
          Authorization: `Bearer ${token}`,
          "Accept-Language": locale,
          "Content-Type": "application/json",
          Accept: "application/json",
        },
      },
    );

    return response.data.status;
  } catch (error) {
    return false;
  }
}

export async function getRecentlyViewedProductsList(
  token: string | null,
  locale: string,
  limit: number = 20,
  productIds?: string[],
) {
  try {
    const params: any = { limit };

    if (productIds?.length) {
      params.productIds = productIds.join(",");
    }

    const headers: any = {
      "Accept-Language": locale,
      "Content-Type": "application/json",
      Accept: "application/json",
    };

    if (token) {
      headers.Authorization = `Bearer ${token}`;
    }

    const response = await axios.get(
      `${API_BASE_URL}/products/recently-viewed`,
      {
        params,
        withCredentials: true,
        headers,
      },
    );

    if (!response?.data?.data?.data?.length) {
      return [];
    }

    return response.data.data.data;
  } catch (error) {
    return [];
  }
}

export const fetchRecentlyViewedProductsByIds = async (
  productIds: string[],
  token: string | null,
  locale: string,
): Promise<{ status: boolean; message: string; data?: any }> => {
  if (!productIds?.length) {
    return {
      status: false,
      message: "No product IDs provided",
    };
  }

  try {
    const headers: any = {
      "Accept-Language": locale,
      "Content-Type": "application/json",
      Accept: "application/json",
    };

    if (token) {
      headers.Authorization = `Bearer ${token}`;
    }

    const location = getSavedLocation();
    let url = `${API_BASE_URL}/products/recently-viewed`;
    if (location) {
      url += `?latitude=${location.lat}&longitude=${location.lng}`;
    }

    const response = await axios.get(url, {
      params: {
        limit: productIds.length,
        productIds: productIds.join(","),
      },
      withCredentials: true,
      headers,
    });

    return {
      status: true,
      message: response.data.message || "Products fetched successfully",
      data: response.data.data,
    };
  } catch (error: any) {
    return {
      status: false,
      message: error.response?.data?.message || "Failed to fetch products",
    };
  }
};
