// Function to process variable taps when success is true
export function AddNewVariation(Varibletaps: any[], data: any, AddVariation: any) {
  const baseProductId = data?.id;
  Varibletaps?.forEach((dataToSend: any) => {
    const varible = dataToSend;
    const info = varible?.info ?? [];
    const convertedArray = info?.reduce((acc: any, obj: any) => {
      acc[obj.Description] = obj.key;
      return acc;
    }, {});
    const jsonString = Object.keys(convertedArray).length === 0 ? null : JSON.stringify(convertedArray);


    const StringimagesArray = varible?.images?.filter((item: any) => typeof item === 'string') || [];
    const FileimagesArray = varible?.images?.filter((item: any) => typeof item !== 'string') || [];
    
    const images = { images: FileimagesArray };
    console.log(FileimagesArray,"FileimagesArray");
    console.log(StringimagesArray,"StringimagesArray");

    const main_photo = (typeof varible?.main_photo === 'string') ? {} : { main_photo: varible?.main_photo };
    
    // const copied_assets = [
    //   ...(typeof varible?.main_photo === 'string' ? [{ main_photo: varible?.main_photo }] : []),
    //   [StringimagesArray]
    // ];
    


    const mappedAttributes = varible.attribute?.map((item: any) => {
      return item?.map((subitem: any) => ({
          attribute_value_id: subitem?.value,
          attribute_id: subitem?.id
      }));
  });
  
  console.log(mappedAttributes, "mappedAttributes");
  
  // Flatten the array of arrays
  const flattenedAttributes = mappedAttributes?.filter(Boolean)?.flat();
  
  const arrayOfObjects = flattenedAttributes?.map((subArray: any, index: any) => {
      console.log(subArray, "subArray");
      console.log(index, "index");
  
      return {
          ...subArray,
      };
  });
  
  console.log(arrayOfObjects, "arrayOfObjects");
  

    const Newproduct = {
      name: {
        en: varible?.name_en,
        ar: varible?.name_ar,
        de: varible?.name_de
      },
      description: {
        en: varible?.description_en,
        ar: varible?.description_ar,
        de: varible?.description_de
      },
      // quantity: varible?.quantity,
      ...images,
      ...main_photo,
      // ...copied_assets,

      info: jsonString,
      price: varible?.price,
      // product_attributes: varible?.attribute?.map((item: any, index: any) => {
      //  return  item?.map((subitem:any,index:any)=>{
      //     return { attribute_value_id: subitem?.value, attribute_id: subitem?.id }
      //   })
      // }),
      product_attributes:arrayOfObjects,
      base_product_id: baseProductId
    };
    console.log(Newproduct);
    AddVariation(Newproduct);
  });
}
