"use server";

import fetchData from "@/api/fetch-data";
import { siteSettingFallback } from "@/lib/utils";
import { cookies } from "next/headers";
import { getToken } from "./cookies";

export const sendFormInputs = async (formInputs, productId) => {
  const token = await getToken();
  // Transform the entire form inputs array
  const transformedData = formInputs.map((field) => {
    // Handle fields with different structures (input vs checkbox)
    if (
      field.inputType === "smalltext" ||
      field.inputType === "largetext" ||
      field.inputType === "number" ||
      field.inputType === "image" ||
      field.inputType === "date" ||
      field.inputType === "time" ||
      field.inputType === "datetime"
    ) {
      let objectToSend = {
        [`fields[${field.id}][type]`]: field.inputType,
        [`fields[${field.id}][sort]`]: field.order,
        [`fields[${field.id}][name]`]: field?.fieldName,
        [`fields[${field.id}][desc]`]: field?.placeHolder,
      };

      if (field?.isRequired) {
        objectToSend = {
          ...objectToSend,
          [`fields[${field.id}][required]`]: field?.isRequired,
        };
      }
      return objectToSend;
    }

    if (
      (field.inputType === "checkbox" || field.inputType === "radio") &&
      field.options &&
      field.options.length > 0
    ) {
      // Reduce the options to create a mapped object
      const optionsMap = field.options.reduce((acc, option, index) => {
        acc[`fields[${field.id}][options][${option.id}][name]`] =
          option.name || `Option ${index + 1}`;
        acc[`fields[${field.id}][options][${option.id}][price]`] = option.price;
        return acc;
      }, {});

      return {
        [`fields[${field.id}][type]`]: field.inputType,
        [`fields[${field.id}][sort]`]: field.order,
        [`fields[${field.id}][name]`]: field?.fieldName,
        [`fields[${field.id}][desc]`]: field?.placeHolder,
        [`fields[${field.id}][required]`]: field?.isRequired ? 1 : 0,
        ...optionsMap,
      };
    }
  });
  // Flatten the transformed data
  const flattenedData = transformedData.reduce((acc, curr) => {
    return { ...acc, ...curr };
  }, {});

  // Convert to FormData
  const formData = new FormData();
  formData.append("id", productId);

  Object.keys(flattenedData).forEach((key) => {
    formData.append(key, flattenedData[key]);
  });
  const url = `${process.env.NEXT_PUBLIC_ENDPOINT}/user/products/custom-fields`;
  try {
    const response = await fetch(url, {
      method: "POST",
      body: formData,
      headers: {
        Authorization: `Bearer ${token}`,
        "Accept-Language": "ar",
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    return result;
  } catch (error) {
    return { error };
  }
};

export const fetchDataInfinite = async (url, pageParam, lang = "ar") => {
  const token = cookies().get("token");

  const response = await fetch(
    `${process.env.NEXT_PUBLIC_ENDPOINT}${url}?page=${pageParam}`,
    {
      headers: {
        "Accept-Language": lang,
        Accept: "application/json",
        Authorization: `Bearer ${token?.value}`,
      },
      credentials: "include",
      cache: "no-store",
    }
  );

  const data = await response.json();
  const currentPage = data?.data?.current_page || 1;
  const lastPage = data?.data?.last_page || 1;
  return {
    currentPage,
    lastPage,
    data,
  };
};

export const fetchDataReturnPromise = async (url, lang = "ar", isProtected) => {
  const token = cookies().get("token");
  try {
    const response = await fetch(`${process.env.NEXT_PUBLIC_ENDPOINT}${url}`, {
      headers: {
        "Accept-Language": lang,
        Authorization: `Bearer ${token?.value}`,
        Accept: "application/json",
      },
      credentials: "include",
      cache: "no-store",
    });
    if (isProtected && response.status === 401) {
      return handelGenerateToken();
      throw new Error("يجب أن تسجل الدخول أولا");
    }

    if (response.status === 403) {
      const data = await response.json();
      throw new Error(data.message);
    }

    if (response.status === 500) {
      throw new Error(
        "حدث خطأ ما حاول مجددًا وإذا استمرت المشكلة اتصل بنا او حاول مرة إخرى"
      );
    }

    return response.json();
  } catch (error) {
    if (error instanceof Error) {
      return {
        status: error.message,
      };
    } else {
      return {
        status: "Something went wrong",
      };
    }
  }
};

export const fetchSiteSettings = async () => {
  const { data } = await fetchData({ endPoint: '/settings' })
  if (data) {
    return { ...data, status: 'dynamic' };
  }
  return siteSettingFallback;
};
