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";

/**
 * Generate headers with API authentication
 */
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.");
  }
}
// // Form functions file
// 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:3340/api/client";
// const key = "2994b43e78e9caf26cd3ca27475783da37919e4768898d41";
// const secret =
//   "9583f140ec4fb8ca0ce82812fb06eae6c9e9b59a999d6fba728a92616ed15297";

// /**
//  * Generate headers with API authentication
//  */
// function generateHeaders(
//   host?: string,
//   extraHeaders?: Record<string, string>,
//   body?: Record<string, any>
// ) {
//   const timeStamp = Date.now();
//   const payload = body
//     ? JSON.stringify(body)
//     : JSON.stringify({ timestamp: timeStamp });
//   const signature = crypto
//     .createHmac("sha256", secret)
//     .update(Buffer.from(payload).toString())
//     .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, formData); // Include formData in signature for POST
//   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.response?.status,
//       error.message
//     );
//     throw new Error(error.response?.data?.message || "Failed to submit form.");
//   }
// }
