import { getToken } from "@/actions/cookies";

const transformFormData = (formData, productId, productQuantity) => {
  // Create a new FormData object
  const formDataToSend = new FormData();

  // Add fixed fields
  formDataToSend.append("item_id", productId);
  formDataToSend.append("item_quantity", productQuantity);

  for (const [key, value] of Object.entries(formData)) {
    const fieldId = key; // Assuming key is already the numeric ID

    try {
      if (Array.isArray(value)) {
        // Handle array values (like checkboxes, multi-select)
        value.forEach((item) => {
          formDataToSend.append(`field[${fieldId}][options][]`, item);
        });
      } else {
        // Handle single values
        if (value instanceof Date) {
          // Determine date type based on the Date object
          const formattedDate = isDateWithTime(value)
            ? formatDateToString(value) // Datetime with time
            : formatDateToDateString(value); // Date only

          formDataToSend.append(`field[${fieldId}]`, formattedDate);
        } else if (value instanceof File) {
          // Handle file uploads
          formDataToSend.append(`field[${fieldId}]`, value);
        } else {
          // Regular single values
          formDataToSend.append(`field[${fieldId}]`, value);
        }
      }
    } catch (error) {
      // Global catch-all case for any unhandled scenarios
      console.warn(`Fallback handling for field ${fieldId}:`, error);

      // Convert to string and append as is
      formDataToSend.append(
        `field[${fieldId}]`,
        value !== null && value !== undefined ? String(value) : ""
      );
    }
  }

  return formDataToSend;
};

// Helper function to check if a Date object includes time information
const isDateWithTime = (date) => {
  return (
    date.getHours() !== 0 ||
    date.getMinutes() !== 0 ||
    date.getSeconds() !== 0 ||
    date.getMilliseconds() !== 0
  );
};

// Helper function to format date to 'YYYY-MM-DD HH:mm'
const formatDateToString = (date) => {
  const pad = (num) => num.toString().padStart(2, "0");

  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
    date.getDate()
  )} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
};

// Helper function to format date to 'YYYY-MM-DD'
const formatDateToDateString = (date) => {
  const pad = (num) => num.toString().padStart(2, "0");

  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
    date.getDate()
  )}`;
};

export default async function postDataClient({
  endPoint,
  body,
  locale = "ar",
  headers = {},
  productId,
  productQuantity,
  ...config
}) {
  let code;
  let response;

  const dataToSend = transformFormData(body, productId, productQuantity);
  const token = await getToken();
  try {
    response = await fetch(`${process.env.NEXT_PUBLIC_ENDPOINT}${endPoint}`, {
      method: "POST",
      body: dataToSend,
      headers: {
        Authorization: ` Bearer ${token}`,
        "Accept-Language": locale,
        Accept: "application/json",
        ...headers,
      },
      ...config,
    });
    code = response.status;

    if (!response.ok) {
      const errorObject = await response.json();
      throw new Error(JSON.stringify(errorObject));
    }
    const data = await response.json();

    return { ...data, error: false, code };
  } catch (error) {
    let parsedError;
    try {
      parsedError = JSON.parse(error.message);
    } catch {
      parsedError = { message: "'Internal Server Error'", details: error };
    }
    return { ...parsedError, error: true, code };
  }
}
