import axios from "axios";
import crypto from "crypto";

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

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

const baseUrl = "https://cms.admin.tezcommerce.com/api/client";
const key = "745f205f13127927d70bacae28042b47479199a98586140e";
const secret =
  "c8323b026ed8179d35df8471f4550fa6b870e6252e3f014adbc08d2991f99acd";

function generateHeaders(host?: string, extraHeaders?: Record<string, string>) {
  const timeStamp = Date.now();
  const body = { timestamp: timeStamp };
  const payload = Buffer.from(JSON.stringify(body)).toString();
  const signature = crypto
    .createHmac("sha256", secret)
    .update(payload)
    .digest("hex");

  return {
    ...extraHeaders,
    "X-AUTH-APIKEY": key,
    "X-AUTH-SIGNATURE": signature,
    "X-AUTH-TIMESTAMP": timeStamp.toString(),
    "Content-Type": "application/json",
    "x-host": host || "localhost:3000",
  };
}

/**
 * GET form fields
 */
export async function fetchFormFields(
  { host, ...rh }: FetchParams,
  uid: string
): Promise<ApiResponse> {
  const headers = generateHeaders(host, rh);
  try {
    const response = await axios.get(`${baseUrl}/form/fields/${uid}`, {
      headers,
    });
    return response.data;
  } catch (error: any) {
    console.error(
      "Fetch form fields error:",
      error.response?.data || error.message
    );
    throw new Error("Failed to fetch form fields.");
  }
}

/**
 * POST form submission
 */
export async function submitFormData(
  { host, ...rh }: FetchParams,
  uid: string,
  formData: Record<string, any>
): Promise<ApiResponse> {
  const headers = generateHeaders(host, rh);
  try {
    const response = await axios.post(
      `${baseUrl}/form/submit/${uid}`,
      formData,
      { headers }
    );
    return response.data;
  } catch (error: any) {
    console.error(
      "Form submission error:",
      error.response?.data || error.message
    );
    throw new Error("Failed to submit form.");
  }
}
