import axios, { AxiosResponse } from "axios";
import crypto from "crypto";

interface FetchBannerDataParams {
  host?: string;
  [key: string]: any;
}

interface ApiResponse {
  success?: boolean;
  data?: any;
  [key: string]: any;
}

export async function fetchAllBanners({
  host,
  ...rh
}: FetchBannerDataParams): Promise<ApiResponse> {
  const baseUrl = "https://cms.admin.tezcommerce.com/api/client";
  const timeStamp = Date.now();

  const key = "745f205f13127927d70bacae28042b47479199a98586140e";
  const secret =
    "c8323b026ed8179d35df8471f4550fa6b870e6252e3f014adbc08d2991f99acd";

  const body = { timestamp: timeStamp };
  const payload = Buffer.from(JSON.stringify(body)).toString();
  const signature = crypto
    .createHmac("sha256", secret)
    .update(payload)
    .digest("hex");

  const headers: Record<string, string> = {
    ...rh,
    "X-AUTH-APIKEY": key,
    "X-AUTH-SIGNATURE": signature,
    "X-AUTH-TIMESTAMP": timeStamp.toString(),
    "Content-Type": "application/json",
    "x-host": host || "localhost:3000",
  };

  // console.log("==== DEBUG fetchAllBanners ====");
  // console.log("Base URL:", baseUrl);
  // console.log("Final URL:", `${baseUrl}/banner/fetch-all-banner`);
  // console.log("Timestamp:", timeStamp);
  // console.log("Headers:", headers);
  // console.log("============================");

  try {
    const response = await axios.get(`${baseUrl}/banner/fetch-all-banner`, {
      headers,
    });
    // console.log("API Response:", response.data);
    return response.data;
  } catch (error: any) {
    console.error("Fetch error details:", {
      message: error.message,
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
    });
    throw new Error("Failed to fetch banners.");
  }
}
