const { FACILITY_ID } = require('../config/SplitManagementDb');
const SplitManagementModel = require('../models/SplitManagementModel')

const fetchAllSplitManagementSettings = async (req, res) => {
    try {
        const splitManagementSettings = await SplitManagementModel.getAllSplitManagementSettings();
        res.send({ status: 1, result: splitManagementSettings })
    } catch (error) {
        console.error('Error fetching split management settings:', error);
        res.send({ status: 0, result: [] })
    }
}

const updateSplitManagementSettings = async (req, res) => {
    try {
        const { splitManagementSettings } = req.body;

        let response = false
        for (let i = 0; i < splitManagementSettings.length; i++) {
            const id = splitManagementSettings[i].id;
            const splitPercentage = splitManagementSettings[i].split_percentage;
            const incomingPercentage = splitManagementSettings[i].incoming_percentage;

            response = await SplitManagementModel.updateSplitManagementSettings(id, splitPercentage, incomingPercentage);
        }
        if (response) {
            res.send({ status: 1, result: response })
        } else {
            res.send({ status: 0, result: response })
        }
    } catch (error) {
        console.error('Error updating split management settings:', error);
        res.send({ status: 0, result: [] })
    }
}


const addBuildOrderSalesOrderToOtherInstallation = async (requestdata,userId,uploaded,values,avalaraTaxAmount,negativeAmount,taxCategory,address,targetedFacilities,productAttachments,isFromEdit,existingOtherInstallationRequestData) => {  
    try {
      const results = [];
      const errors = [];
      
      // Loop through each facility ID in targetedFacilities array
      for (const facilityId of targetedFacilities) {
        try {
          console.log(`Processing facility ID: ${facilityId}`);
          let filteredProducts = values.products.filter(product => product.facility_id == facilityId);
          let filteredServices = values.selectedServices.filter(service => service.facility_id == facilityId);
          console.log('filteredProducts', filteredProducts)
          if(filteredProducts?.length > 0 || filteredServices?.length > 0){
            const matchingOtherInstallationRequestData = isFromEdit ? existingOtherInstallationRequestData?.find(data => data?.targeted_facility_id == facilityId) : null;
          // Use the new comprehensive model function for each facility
          const result = await SplitManagementModel.addCompleteSalesOrderToOtherInstallation(
            facilityId,
            requestdata,
            userId,
            uploaded,
            values,
            avalaraTaxAmount,
            negativeAmount,
            taxCategory,
            address,
            productAttachments,
            isFromEdit,
            matchingOtherInstallationRequestData
          );
          
          if (result.success) {
            console.log(`Sales order successfully created in facility ${facilityId}:`, result.data);
            results.push({
              facilityId: facilityId,
              success: true,
              message: 'Sales order created successfully in ' + result.data.installationName,
              data: result.data
            });
          } else {
            console.error(`Failed to create sales order in facility ${facilityId}:`, result.message);
            errors.push({
              facilityId: facilityId,
              success: false,
              message: result.message
            });
            continue;
          }
            /* ======================================================
              2️⃣ CREATE MIRROR BUILD ORDER IN CURRENT FACILITY
            ====================================================== */
            if(result?.success){
            const mirrorRequestData = {
              ...requestdata,
              min_payment_status: 1,
              origin_facility_id: facilityId,
              origin_facility_request_id: result?.data?.requestId,
              for_parent_facility: 2,  // 🔥 MIRROR
              new_order: 0,
            };

            const mirrorResult =
              await SplitManagementModel.addCompleteSalesOrderToCurrentInstallation(
                facilityId,
                { ...mirrorRequestData },
                userId,
                uploaded,
                values,             // SAME products
                avalaraTaxAmount,
                negativeAmount,
                taxCategory,
                address,
                productAttachments,
                isFromEdit
              );

            if (!mirrorResult?.success) {
              errors.push({
                facilityId,
                message: 'Mirror creation failed in current installation'
              });
              continue;
            }

            results.push({
              facilityId,
              otherInstallation: result?.data,
              currentInstallationMirror: mirrorResult.data
            });
          }
        } else {
          console.log(`No products found for facility ${facilityId}. Skipping this facility.`);
        }
        } catch (facilityError) {
          console.error(`Error processing facility ${facilityId}:`, facilityError);
          errors.push({
            facilityId: facilityId,
            success: false,
            message: 'Error processing facility: ' + facilityError.message
          });
        }
      }
      
      // Determine overall success based on results
      const hasSuccessfulResults = results.length > 0;
      const hasErrors = errors.length > 0;
      
      if (hasSuccessfulResults && !hasErrors) {
        // All facilities processed successfully
        return {
          success: true,
          message: `Sales orders created successfully in ${results.length} facility(ies)`,
          data: results,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: results.length,
            failed: 0
          }
        };
      } else if (hasSuccessfulResults && hasErrors) {
        // Partial success - some facilities succeeded, some failed
        return {
          success: true,
          message: `Sales orders created in ${results.length} out of ${targetedFacilities.length} facilities`,
          data: results,
          errors: errors,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: results.length,
            failed: errors.length
          }
        };
      } else {
        // All facilities failed
        return {
          success: false,
          message: 'Failed to create sales orders in any facility',
          errors: errors,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: 0,
            failed: errors.length
          }
        };
      }
      
    } catch (error) {
      console.error('Error in addBuildOrderSalesOrderToOtherInstallation:', error);
      return {
        success: false,
        message: 'Internal server error: ' + error.message
      };
    }
  }

  const addBuildOrderSalesOrderToCurrentInstallation = async (requestdata,userId,uploaded,values,avalaraTaxAmount,negativeAmount,taxCategory,address,targetedFacilities) => {  
    try {
      const facilityId = FACILITY_ID;
      const results = [];
      const errors = [];
      
      try {
        console.log(`Processing facility ID: ${facilityId}`);
        
        // Use the new comprehensive model function for each facility
        const result = await SplitManagementModel.addCompleteSalesOrderToCurrentInstallation(
          facilityId,
          requestdata,
          userId,
          uploaded,
          values,
          avalaraTaxAmount,
          negativeAmount,
          taxCategory,
          address,
        );
        
        if (result.success) {
          console.log(`Sales order successfully created in facility ${facilityId}:`, result.data);
          results.push({
            facilityId: facilityId,
            success: true,
            message: 'Sales order created successfully in ' + result.data.installationName,
            data: result.data
          });
        } else {
          console.error(`Failed to create sales order in facility ${facilityId}:`, result.message);
          errors.push({
            facilityId: facilityId,
            success: false,
            message: result.message
          });
        }
      } catch (facilityError) {
        console.error(`Error processing facility ${facilityId}:`, facilityError);
        errors.push({
          facilityId: facilityId,
          success: false,
          message: 'Error processing facility: ' + facilityError.message
        });
      }
      
      // Determine overall success based on results
      const hasSuccessfulResults = results.length > 0;
      const hasErrors = errors.length > 0;
      
      if (hasSuccessfulResults && !hasErrors) {
        // All facilities processed successfully
        return {
          success: true,
          message: `Sales orders created successfully in current installation`,
          data: results,
          summary: {
            totalProcessed: 1,
            successful: 1,
            failed: 0
          }
        };
      } else if (hasSuccessfulResults && hasErrors) {
        // Partial success - some facilities succeeded, some failed
        return {
          success: true,
          message: `Sales orders created in current installation`,
          data: results,
          errors: errors,
          summary: {
            totalProcessed: 1,
            successful: results.length,
            failed: errors.length
          }
        };
      } else {
        // All facilities failed
        return {
          success: false,
          message: 'Failed to create sales orders in current installation',
          errors: errors,
          summary: {
            totalProcessed: 1,
            successful: 0,
            failed: errors.length
          }
        };
      }
      
    } catch (error) {
      console.error('Error in addBuildOrderSalesOrderToCurrentInstallation:', error);
      return {
        success: false,
        message: 'Internal server error: ' + error.message
      };
    }
  }

  const addMirrorOrderSalesOrderToOtherInstallation = async (requestdata,userId,uploaded,values,avalaraTaxAmount,negativeAmount,taxCategory,address,targetedFacilities,mirrorData) => {  
    try {
      const results = [];
      const errors = [];
      
      // Loop through each facility ID in targetedFacilities array
      for (const facilityId of targetedFacilities) {
        try {
          console.log(`Processing facility ID: ${facilityId}`);
          console.log(`Processing values`, values);
          
          // Use the new comprehensive model function for each facility
          const result = await SplitManagementModel.addMirrorCompleteSalesOrderToOtherInstallation(
            facilityId,
            requestdata,
            userId,
            uploaded,
            values,
            avalaraTaxAmount,
            negativeAmount,
            taxCategory,
            address,
            mirrorData
          );
          
          if (result.success) {
            console.log(`mirror Sales order successfully created in facility ${facilityId}:`, result.data);
            results.push({
              facilityId: facilityId,
              success: true,
              message: 'mirror Sales order created successfully in ' + result.data.installationName,
              data: result.data
            });
          } else {
            console.error(`Failed to create mirror sales order in facility ${facilityId}:`, result.message);
            errors.push({
              facilityId: facilityId,
              success: false,
              message: result.message
            });
          }
        } catch (facilityError) {
          console.error(`Error processing mirror facility ${facilityId}:`, facilityError);
          errors.push({
            facilityId: facilityId,
            success: false,
            message: 'Error processing mirror facility: ' + facilityError.message
          });
        }
      }
      
      // Determine overall success based on results
      const hasSuccessfulResults = results.length > 0;
      const hasErrors = errors.length > 0;
      
      if (hasSuccessfulResults && !hasErrors) {
        // All facilities processed successfully
        return {
          success: true,
          message: `mirror Sales orders created successfully in ${results.length} facility(ies)`,
          data: results,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: results.length,
            failed: 0
          }
        };
      } else if (hasSuccessfulResults && hasErrors) {
        // Partial success - some facilities succeeded, some failed
        return {
          success: true,
          message: `mirror Sales orders created in ${results.length} out of ${targetedFacilities.length} facilities`,
          data: results,
          errors: errors,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: results.length,
            failed: errors.length
          }
        };
      } else {
        // All facilities failed
        return {
          success: false,
          message: 'Failed to create mirror sales orders in any facility',
          errors: errors,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: 0,
            failed: errors.length
          }
        };
      }
      
    } catch (error) {
      console.error('Error in addMirrorOrderSalesOrderToOtherInstallation:', error);
      return {
        success: false,
        message: 'Internal server error: ' + error.message
      };
    }
  }

  const updateMirrorOrderSalesOrderToOtherInstallation = async (requestdata,userId,uploaded,values,avalaraTaxAmount,negativeAmount,taxCategory,address,targetedFacilities,mirrorData,request_id) => {  
    try {
      const results = [];
      const errors = [];
      
      // Loop through each facility ID in targetedFacilities array
      for (const facilityId of targetedFacilities) {
        try {
          
          // Use the new comprehensive model function for each facility
          const result = await SplitManagementModel.updateMirrorCompleteSalesOrderToOtherInstallation(
            facilityId,
            requestdata,
            userId,
            uploaded,
            values,
            avalaraTaxAmount,
            negativeAmount,
            taxCategory,
            address,
            mirrorData,
            request_id
          );
          
          if (result.success) {
            console.log(`mirror Sales order successfully updated in facility ${facilityId}:`, result.data);
            results.push({
              facilityId: facilityId,
              success: true,
              message: 'mirror Sales order updated successfully in ' + result.data.installationName,
              data: result.data
            });
          } else {
            console.error(`Failed to update mirror sales order in facility ${facilityId}:`, result.message);
            errors.push({
              facilityId: facilityId,
              success: false,
              message: result.message
            });
          }
        } catch (facilityError) {
          console.error(`Error processing mirror facility ${facilityId}:`, facilityError);
          errors.push({
            facilityId: facilityId,
            success: false,
            message: 'Error processing mirror facility: ' + facilityError.message
          });
        }
      }
      
      // Determine overall success based on results
      const hasSuccessfulResults = results.length > 0;
      const hasErrors = errors.length > 0;
      
      if (hasSuccessfulResults && !hasErrors) {
        // All facilities processed successfully
        return {
          success: true,
          message: `mirror Sales orders updated successfully in ${results.length} facility(ies)`,
          data: results,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: results.length,
            failed: 0
          }
        };
      } else if (hasSuccessfulResults && hasErrors) {
        // Partial success - some facilities succeeded, some failed
        return {
          success: true,
          message: `mirror Sales orders updated in ${results.length} out of ${targetedFacilities.length} facilities`,
          data: results,
          errors: errors,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: results.length,
            failed: errors.length
          }
        };
      } else {
        // All facilities failed
        return {
          success: false,
          message: 'Failed to update mirror sales orders in any facility',
          errors: errors,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: 0,
            failed: errors.length
          }
        };
      }
      
    } catch (error) {
      console.error('Error in updateMirrorOrderSalesOrderToOtherInstallation:', error);
      return {
        success: false,
        message: 'Internal server error: ' + error.message
      };
    }
  }


const deleteBuildOrderFromOtherInstallations = async (requestId, targetedFacilities) => {  
    try {
      const results = [];
      const errors = [];
      
      // Loop through each facility ID in targetedFacilities array
      for (const facilityId of targetedFacilities) {
        try {
          console.log(`Deleting build order from facility ID: ${facilityId}`);
          
          // Use the delete model function for each facility
          const result = await SplitManagementModel.deleteCompleteSalesOrderFromOtherInstallation(
            facilityId,
            requestId
          );
          
          if (result.success) {
            console.log(`Build order successfully deleted from facility ${facilityId}:`, result.data);

            // Also delete the mirror build order created in CURRENT installation for this facility
            // In current DB, this mirror row is stored with:
            //   origin_facility_id = facilityId
            //   origin_facility_request_id = result.data.requestId (the target facility's request id)
            //   for_parent_facility = 2
            const mirrorDeleteResult = await SplitManagementModel.deleteCompleteSalesOrderFromCurrentInstallation(
              facilityId,
              result?.data?.requestId
            );

            if (!mirrorDeleteResult?.success) {
              console.error(`Failed to delete mirror build order in current installation for facility ${facilityId}:`, mirrorDeleteResult?.message);
              errors.push({
                facilityId: facilityId,
                success: false,
                message: mirrorDeleteResult?.message || 'Failed to delete mirror build order in current installation'
              });
            }

            results.push({
              facilityId: facilityId,
              success: true,
              message: 'Build order deleted successfully from ' + result.data.installationName,
              data: {
                otherInstallation: result.data,
                currentInstallationMirror: mirrorDeleteResult?.data || null
              }
            });
          } else {
            console.error(`Failed to delete build order from facility ${facilityId}:`, result.message);
            errors.push({
              facilityId: facilityId,
              success: false,
              message: result.message
            });
          }
        } catch (facilityError) {
          console.error(`Error processing facility ${facilityId}:`, facilityError);
          errors.push({
            facilityId: facilityId,
            success: false,
            message: 'Error processing facility: ' + facilityError.message
          });
        }
      }
      
      // Determine overall success based on results
      const hasSuccessfulResults = results.length > 0;
      const hasErrors = errors.length > 0;
      
      if (hasSuccessfulResults && !hasErrors) {
        // All facilities processed successfully
        return {
          success: true,
          message: `Build orders deleted successfully from ${results.length} facility(ies)`,
          data: results,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: results.length,
            failed: 0
          }
        };
      } else if (hasSuccessfulResults && hasErrors) {
        // Partial success - some facilities succeeded, some failed
        return {
          success: true,
          message: `Build orders deleted from ${results.length} out of ${targetedFacilities.length} facilities`,
          data: results,
          errors: errors,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: results.length,
            failed: errors.length
          }
        };
      } else {
        // All facilities failed
        return {
          success: false,
          message: 'Failed to delete build orders from any facility',
          errors: errors,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: 0,
            failed: errors.length
          }
        };
      }
      
    } catch (error) {
      console.error('Error in deleteBuildOrderFromOtherInstallations:', error);
      return {
        success: false,
        message: 'Internal server error: ' + error.message
      };
    }
  }

  const BuildOrderFromOtherInstallationsDelete = async (requestId, targetedFacilities, originBuildOrderId) => {  
    try {
      const results = [];
      const errors = [];
      
      // Loop through each facility ID in targetedFacilities array
      for (const facilityId of targetedFacilities) {
        try {
          console.log(`Deleting build order from facility ID: ${facilityId}`);
          
          // Use the delete model function for each facility
          const result = await SplitManagementModel.BuildOrderFromOtherInstallationsDelete(
            facilityId,
            requestId
          );
          
          if (result.success) {
            console.log(`Build order successfully deleted from facility ${facilityId}:`, result.data);

            // Also delete the mirror build order created in CURRENT installation for this facility
            // In current DB, this mirror row is stored with:
            //   origin_facility_id = facilityId
            //   origin_facility_request_id = result.data.requestId (the target facility's request id)
            //   for_parent_facility = 2
            const mirrorDeleteResult = await SplitManagementModel.BuildOrderFromOtherInstallationsDeleteMirror(
              facilityId,
              originBuildOrderId
            );

            if (!mirrorDeleteResult?.success) {
              console.error(`Failed to delete mirror build order in current installation for facility ${facilityId}:`, mirrorDeleteResult?.message);
              errors.push({
                facilityId: facilityId,
                success: false,
                message: mirrorDeleteResult?.message || 'Failed to delete mirror build order in current installation'
              });
            }

            results.push({
              facilityId: facilityId,
              success: true,
              message: 'Build order deleted successfully from ' + result.data.installationName,
              data: {
                otherInstallation: result.data,
                currentInstallationMirror: mirrorDeleteResult?.data || null
              }
            });
          } else {
            console.error(`Failed to delete build order from facility ${facilityId}:`, result.message);
            errors.push({
              facilityId: facilityId,
              success: false,
              message: result.message
            });
          }
        } catch (facilityError) {
          console.error(`Error processing facility ${facilityId}:`, facilityError);
          errors.push({
            facilityId: facilityId,
            success: false,
            message: 'Error processing facility: ' + facilityError.message
          });
        }
      }
      
      // Determine overall success based on results
      const hasSuccessfulResults = results.length > 0;
      const hasErrors = errors.length > 0;
      
      if (hasSuccessfulResults && !hasErrors) {
        // All facilities processed successfully
        return {
          success: true,
          message: `Build orders deleted successfully from ${results.length} facility(ies)`,
          data: results,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: results.length,
            failed: 0
          }
        };
      } else if (hasSuccessfulResults && hasErrors) {
        // Partial success - some facilities succeeded, some failed
        return {
          success: true,
          message: `Build orders deleted from ${results.length} out of ${targetedFacilities.length} facilities`,
          data: results,
          errors: errors,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: results.length,
            failed: errors.length
          }
        };
      } else {
        // All facilities failed
        return {
          success: false,
          message: 'Failed to delete build orders from any facility',
          errors: errors,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: 0,
            failed: errors.length
          }
        };
      }
      
    } catch (error) {
      console.error('Error in deleteBuildOrderFromOtherInstallations:', error);
      return {
        success: false,
        message: 'Internal server error: ' + error.message
      };
    }
  }

    const deleteMirrorBuildOrderFromOtherInstallations = async (requestId, targetedFacilities) => {  
    console.log('requestId.......',requestId);
    console.log('targetedFacilities.......',targetedFacilities);
    try {
      const results = [];
      const errors = [];
      
      // Loop through each facility ID in targetedFacilities array
      for (const facilityId of targetedFacilities) {
        try {
          console.log(`Deleting build order from facility ID: ${facilityId}`);
          // Use the delete model function for each facility
          const result = await SplitManagementModel.deleteCompleteSalesOrderFromOtherInstallation(
            facilityId,
            requestId
          );
          if (result.success) {
            console.log(`Build order successfully deleted from facility ${facilityId}:`, result.data);

            // Also delete the mirror build order created in CURRENT installation for this facility
            // In current DB, this mirror row is stored with:
            //   origin_facility_id = facilityId
            //   origin_facility_request_id = result.data.requestId (the target facility's request id)
            //   for_parent_facility = 2
            const mirrorDeleteResult = await SplitManagementModel.deleteCompleteSalesOrderFromCurrentInstallation(
              facilityId,
              result?.data?.requestId
            );

            if (!mirrorDeleteResult?.success) {
              console.error(`Failed to delete mirror build order in current installation for facility ${facilityId}:`, mirrorDeleteResult?.message);
              errors.push({
                facilityId: facilityId,
                success: false,
                message: mirrorDeleteResult?.message || 'Failed to delete mirror build order in current installation'
              });
            }

            results.push({
              facilityId: facilityId,
              success: true,
              message: 'Build order deleted successfully from ' + result.data.installationName,
              data: {
                otherInstallation: result.data,
                currentInstallationMirror: mirrorDeleteResult?.data || null
              }
            });
          } else {
            console.error(`Failed to delete build order from facility ${facilityId}:`, result.message);
            errors.push({
              facilityId: facilityId,
              success: false,
              message: result.message
            });
          }
        } catch (facilityError) {
          console.error(`Error processing facility ${facilityId}:`, facilityError);
          errors.push({
            facilityId: facilityId,
            success: false,
            message: 'Error processing facility: ' + facilityError.message
          });
        }
      }
      
      // Determine overall success based on results
      const hasSuccessfulResults = results.length > 0;
      const hasErrors = errors.length > 0;
      
      if (hasSuccessfulResults && !hasErrors) {
        // All facilities processed successfully
        return {
          success: true,
          message: `Build orders deleted successfully from ${results.length} facility(ies)`,
          data: results,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: results.length,
            failed: 0
          }
        };
      } else if (hasSuccessfulResults && hasErrors) {
        // Partial success - some facilities succeeded, some failed
        return {
          success: true,
          message: `Build orders deleted from ${results.length} out of ${targetedFacilities.length} facilities`,
          data: results,
          errors: errors,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: results.length,
            failed: errors.length
          }
        };
      } else {
        // All facilities failed
        return {
          success: false,
          message: 'Failed to delete build orders from any facility',
          errors: errors,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: 0,
            failed: errors.length
          }
        };
      }
      
    } catch (error) {
      console.error('Error in deleteBuildOrderFromOtherInstallations:', error);
      return {
        success: false,
        message: 'Internal server error: ' + error.message
      };
    }
  }

  const getRequestByMirrorBuildOrder = async (requestId, facilityId) => {
    try {
      const existingRequest = await SplitManagementModel.getRequestByMirrorBuildOrder(
        requestId,
        facilityId
      );
      return existingRequest;
    } catch (error) {
      console.error('Error in getRequestByMirrorBuildOrder:', error);
      return null;
    }
  };

  const deleteMirrorOrderFromOtherInstallations = async (requestId, targetedFacilities) => {  
    try {
      const results = [];
      const errors = [];
      
      // Loop through each facility ID in targetedFacilities array
      for (const facilityId of targetedFacilities) {
        try {
          console.log(`Deleting mirror order from facility ID: ${facilityId}`);
          
          // Use the delete model function for each facility
          const result = await SplitManagementModel.deleteCompleteMirrorSalesOrderFromOtherInstallation(
            facilityId,
            requestId
          );
          
          if (result.success) {
            console.log(`mirror order successfully deleted from facility ${facilityId}:`, result.data);
            results.push({
              facilityId: facilityId,
              success: true,
              message: 'mirror order deleted successfully from ' + result.data.installationName,
              data: result.data
            });
          } else {
            console.error(`Failed to delete mirror order from facility ${facilityId}:`, result.message);
            errors.push({
              facilityId: facilityId,
              success: false,
              message: result.message
            });
          }
        } catch (facilityError) {
          console.error(`Error processing facility ${facilityId}:`, facilityError);
          errors.push({
            facilityId: facilityId,
            success: false,
            message: 'Error processing facility: ' + facilityError.message
          });
        }
      }
      
      // Determine overall success based on results
      const hasSuccessfulResults = results.length > 0;
      const hasErrors = errors.length > 0;
      
      if (hasSuccessfulResults && !hasErrors) {
        // All facilities processed successfully
        return {
          success: true,
          message: `Mirror orders deleted successfully from ${results.length} facility(ies)`,
          data: results,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: results.length,
            failed: 0
          }
        };
      } else if (hasSuccessfulResults && hasErrors) {
        // Partial success - some facilities succeeded, some failed
        return {
          success: true,
          message: `Mirror orders deleted from ${results.length} out of ${targetedFacilities.length} facilities`,
          data: results,
          errors: errors,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: results.length,
            failed: errors.length
          }
        };
      } else {
        // All facilities failed
        return {
          success: false,
          message: 'Failed to delete Mirror orders from any facility',
          errors: errors,
          summary: {
            totalProcessed: targetedFacilities.length,
            successful: 0,
            failed: errors.length
          }
        };
      }
      
    } catch (error) {
      console.error('Error in deleteMirrorOrderFromOtherInstallations:', error);
      return {
        success: false,
        message: 'Internal server error: ' + error.message
      };
    }
  }

  const updateMirrorOrderStatusFromOtherInstallations = async (originRequestId,targetFacilityId,status,receivedStatus) => {  
    try {
      const results = [];
      const errors = [];
      
      // Loop through each facility ID in targetedFacilities array
      for (const facilityId of targetFacilityId) {
        try {
          console.log(`Status updating mirror order from facility ID: ${facilityId}`);
          
          // Use the delete model function for each facility
          const result = await SplitManagementModel.updateSplitMirrorStatus(
            originRequestId,
            facilityId,
            status,
            receivedStatus
          );
          
          if (result.success) {
            console.log(`mirror order successfully status updated from facility ${facilityId}:`, result?.data);
            results.push({
              facilityId: facilityId,
              success: true,
              message: 'mirror order status updated successfully from ' + result?.data?.installationName,
              data: result?.data
            });
          } else {
            console.error(`Failed to status update mirror order from facility ${facilityId}:`, result?.message);
            errors.push({
              facilityId: facilityId,
              success: false,
              message: result?.message
            });
          }
        } catch (facilityError) {
          console.error(`Error processing facility ${facilityId}:`, facilityError);
          errors.push({
            facilityId: facilityId,
            success: false,
            message: 'Error processing facility: ' + facilityError?.message
          });
        }
      }
      
      // Determine overall success based on results
      const hasSuccessfulResults = results?.length > 0;
      const hasErrors = errors?.length > 0;
      
      if (hasSuccessfulResults && !hasErrors) {
        // All facilities processed successfully
        return {
          success: true,
          message: `Mirror orders updated successfully from ${results?.length} facility(ies)`,
          data: results,
          summary: {
            totalProcessed: targetFacilityId?.length,
            successful: results?.length,
            failed: 0
          }
        };
      } else if (hasSuccessfulResults && hasErrors) {
        // Partial success - some facilities succeeded, some failed
        return {
          success: true,
          message: `Mirror orders updated from ${results?.length} out of ${targetFacilityId?.length} facilities`,
          data: results,
          errors: errors,
          summary: {
            totalProcessed: targetFacilityId?.length,
            successful: results?.length,
            failed: errors?.length
          }
        };
      } else {
        // All facilities failed
        return {
          success: false,
          message: 'Failed to updating Mirror orders from any facility',
          errors: errors,
          summary: {
            totalProcessed: targetFacilityId?.length,
            successful: 0,
            failed: errors?.length
          }
        };
      }
      
    } catch (error) {
      console.error('Error in mirror order status update from other installations:', error);
      return {
        success: false,
        message: 'Internal server error: ' + error?.message
      };
    }
  }

  const transferProductStockToOtherInstallation = async (productData,facility_type,requestId,parentFacilityId,productId) => {
    try {
      let facilityId =  parentFacilityId  || facility_type?.[0]?.id //need to add data in this installation
      
      // Use the model function to transfer stock
      const result = await SplitManagementModel.transferProductStockToOtherInstallation(
        facilityId,
        productData
      );
      
      if (result.success) {
        // const update = await SplitManagementModel?.updateCustomerOrderProductTransferStatusOnOtherInstallation(productId,requestId,"",1)
        console.log('Product stock successfully transferred to other installation:', result);
        return {
          success: true,
          message: `Product ${result.action === 'updated' ? 'stock updated' : 'created'} successfully in ${result.data.installationName}`,
          data: result.data
        };
      } else {
        console.error('Failed to transfer product stock to other installation:', result.message);
        return {
          success: false,
          message: result.message
        };
      }
      
    } catch (error) {
      console.error('Error in transferProductStockToOtherInstallation:', error);
      return {
        success: false,
        message: 'Internal server error: ' + error.message
      };
    }
  }

  const updateTargetedFacilityHoldStatusFromOtherInstallations = async (originRequestId, targetFacilityId, project,jobHoldData) => {
    try {
      const results = [];
      const errors = [];

      // Loop through each facility ID in targetFacilityId array
      for (const facilityId of targetFacilityId) {
        try {
          console.log(`Updating hold status for mirror order from facility ID: ${facilityId} with hold status: ${project.hold}`);

          const result = await SplitManagementModel.updateTargetedFacilityHoldStatus(
            originRequestId,
            facilityId,
            project,
            jobHoldData
          );

          if (result.success) {
            console.log(`Mirror order hold status successfully updated for facility ${facilityId}:`, result);
            results.push({
              facilityId: facilityId,
              success: true,
              message: 'Mirror order hold status updated successfully for ' + facilityId, // Assuming facilityId can be used as a name if installationName is not returned
              data: result
            });
          } else {
            console.error(`Failed to update mirror order hold status for facility ${facilityId}:`, result.message);
            errors.push({
              facilityId: facilityId,
              success: false,
              message: result.message
            });
          }
        } catch (facilityError) {
          console.error(`Error processing facility ${facilityId} for hold status update:`, facilityError);
          errors.push({
            facilityId: facilityId,
            success: false,
            message: 'Error processing facility for hold status update: ' + facilityError.message
          });
        }
      }

      const hasSuccessfulResults = results.length > 0;
      const hasErrors = errors.length > 0;

      if (hasSuccessfulResults && !hasErrors) {
        return {
          success: true,
          message: `Mirror orders hold status updated successfully for ${results.length} facility(ies)`,
          data: results,
          summary: {
            totalProcessed: targetFacilityId.length,
            successful: results.length,
            failed: 0
          }
        };
      } else if (hasSuccessfulResults && hasErrors) {
        return {
          success: true,
          message: `Mirror orders hold status updated for ${results.length} out of ${targetFacilityId.length} facilities`,
          data: results,
          errors: errors,
          summary: {
            totalProcessed: targetFacilityId.length,
            successful: results.length,
            failed: errors.length
          }
        };
      } else {
        return {
          success: false,
          message: 'Failed to update Mirror orders hold status for any facility',
          errors: errors,
          summary: {
            totalProcessed: targetFacilityId.length,
            successful: 0,
            failed: errors.length
          }
        };
      }

    } catch (error) {
      console.error('Error in updateTargetedFacilityHoldStatusFromOtherInstallations:', error);
      return {
        success: false,
        message: 'Internal server error: ' + error.message
      };
    }
  }

  const updateBuildOrderToOtherInstallation = async (targetedFacilities,request_id, data) => {  
    console.log('targetedFacilities ==== ', targetedFacilities)
    try {
      const results = [];
      const errors = [];
      
      // Loop through each facility ID in targetedFacilities array
      for (const facilityId of targetedFacilities) {
        try {
          console.log(`Updating build order to facility ID: ${facilityId}`);
          const updatedResult = await SplitManagementModel.updateBuildOrderToOtherInstallation(
            facilityId,
            request_id,
            data
          );
          if (updatedResult.success) {
            console.log(`Build order successfully updated to facility ${facilityId}:`, updatedResult.data);
          
          }
          else {
            console.error(`Failed to update build order to facility ${facilityId}:`, updatedResult.message);
            errors.push({
              facilityId: facilityId,
              success: false,
              message: updatedResult.message
            });
          }
        } catch (facilityError) {
          console.error(`Error processing facility ${facilityId}:`, facilityError);
          errors.push({
            facilityId: facilityId,
            success: false,
            message: 'Error processing facility: ' + facilityError.message
          });
        }
      }
      const hasSuccessfulResults = results.length > 0;
      const hasErrors = errors.length > 0;
      
      if (hasSuccessfulResults && !hasErrors) {
        return {
          success: true,
          message: `Build orders updated successfully to ${results.length} facility(ies)`,
          data: results,
        };
      } else if (hasSuccessfulResults && hasErrors) {
        return {
          success: true,
          message: `Build orders updated to ${results.length} out of ${targetedFacilities.length} facilities`,
          data: results,
          errors: errors,
        };
      }else{
        return {
          success: false,
          message: 'Failed to update Build orders to any facility',
          errors: errors,
        };
      }
    } catch (error) {
      console.error('Error in updateBuildOrderToOtherInstallation:', error);
      return {
        success: false,
        message: 'Internal server error: ' + error.message
      };
    }
  }

const getOtherInstallationRequestData = async (originRequestId, targetFacilityId) => {
    try {
      const results = [];
      for (const facilityId of targetFacilityId) {
        const result = await SplitManagementModel.getOtherInstallationRequestData(originRequestId, facilityId);
        if(result){
          const insertData ={
            ...result,
            targeted_facility_id: facilityId
          }
          results.push(insertData);
        }else{
          return null
        }
      }
      if(results.length > 0){
        return results;
      }else{
        return [];
      }
    } catch (error) {
        console.error('Error in getOtherInstallationRequestData:', error);
        return { success: false, message: 'Internal server error: ' + error.message };
    }
}

module.exports = {
    fetchAllSplitManagementSettings,
    updateSplitManagementSettings,
    addBuildOrderSalesOrderToOtherInstallation,
    addBuildOrderSalesOrderToCurrentInstallation,
    deleteBuildOrderFromOtherInstallations,
    BuildOrderFromOtherInstallationsDelete,
    transferProductStockToOtherInstallation,
    addMirrorOrderSalesOrderToOtherInstallation,
    updateMirrorOrderSalesOrderToOtherInstallation,
    deleteMirrorOrderFromOtherInstallations,
    updateMirrorOrderStatusFromOtherInstallations,
    updateTargetedFacilityHoldStatusFromOtherInstallations,
    updateBuildOrderToOtherInstallation,
    deleteMirrorBuildOrderFromOtherInstallations,
    getRequestByMirrorBuildOrder,
    getOtherInstallationRequestData
};