const { Op } = require("sequelize");
const dbSAPPS = require("../../helpers/db");
require("dotenv").config();

module.exports = {
  generateDocumentNo,
  getSalesItemPlanById,
  getEstimateByPlanId,
  getRealizationByPlanId,
  getAll,
  generateEstimate,
  generateRealization,
  updateEstimate,
  filter,
  option,
  count,
  create,
  update,
  enabled,
  delete: _delete,
  deleteEstimate,
};

async function getAll() {
  try {
    const salesPlans = await dbSAPPS.SalesPlan.findAll({
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.Company,
          attributes: ["id", "display_name"],
          as: "company",
        },
        {
          model: dbSAPPS.Territory,
          attributes: ["id", "display_name"],
          as: "territory",
        },
        {
          model: dbSAPPS.Period,
          attributes: ["id", "display_name"],
          as: "period",
        },
        {
          model: dbSAPPS.SalesPlanItem,
          as: "salesplanitems",
          attributes: [
            "id",
            "salesplan_id",
            "customer_id",
            "item_id",
            "quantity",
            "price",
            "total_gross",
            "discount",
            "nett_price",
            "total_estimate",
            "remarks",
          ],
          include: [
            {
              model: dbSAPPS.Item,
              as: "item",
              attributes: ["id", "display_name"],
            },
            {
              model: dbSAPPS.CustomerList,
              as: "customer",
              // attributes: ["id", "display_name"],
            },
          ],
        },
      ],
    });

    const data = await Promise.all(
      salesPlans.map(async (salesPlan) => {
        const items = await Promise.all(
          salesPlan?.salesplanitems.map(async (salesPlanItem) => {
            const estimate = await dbSAPPS.SalesPlanEstimate.findOne({
              where: {
                salesplan_id: salesPlan.id,
                type: "estimation",
                salesplanitem_id: salesPlanItem.id,
              },
            });
            const realization = await dbSAPPS.SalesPlanEstimate.findOne({
              where: {
                salesplan_id: salesPlan.id,
                type: "realization",
                salesplanitem_id: salesPlanItem.id,
              },
            });
            return {
              ...salesPlanItem.dataValues,
              estimate: estimate || [],
              realization: realization || [],
            };
          })
        );
        return {
          ...salesPlan.dataValues,
          salesplanitems: items,
        };
      })
    );

    return {
      salesPlans: data,
      success: true,
      message: "Data loaded successfully!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to load data!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function filter(params) {
  const filterConditions = {};

  if (params.enabled) {
    filterConditions.enabled = {
      [Op.eq]: params.enabled === "1" ? true : false,
    };
  }

  try {
    const salesPlans = await dbSAPPS.SalesPlan.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]], // Opsional: Mengurutkan hasil berdasarkan kolom 'modified'
      include: [
        {
          model: dbSAPPS.Company,
          as: "company",
          attributes: ["id", "display_name"],
        },
      ],
    });

    return {
      success: true,
      salesPlans,
      message: "Data loaded successfully!",
    };
  } catch (error) {
    console.error("Error retrieving Data: ", error);
    const errorMessage =
      error.message || "Failed to retrieve Data. Please try again later.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function option() {
  try {
    const salesPlans = await dbSAPPS.SalesPlan.findAll({
      attributes: ["id", "territory_id", "doc_no", "company_id", "period_id"],
      where: { enabled: true },
      order: [["doc_no", "ASC"]],
      include: [
        {
          model: dbSAPPS.Company,
          as: "company",
          attributes: ["id", "display_name"],
        },
      ],
    });

    return {
      success: true,
      salesPlans,
      message: "Data loaded successfully!",
    };
  } catch (error) {
    console.error("Error retrieving Data: ", error);
    const errorMessage =
      error.message || "Failed to retrieve Data. Please try again later.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function count() {
  try {
    const count = await dbSAPPS.SalesPlan.count({
      where: { enabled: true },
    });

    return {
      success: true,
      count,
      message: "Data loaded successfully!",
    };
  } catch (error) {
    console.error("Error counting Data: ", error);
    return {
      success: false,
      message: "Failed to retrieve Data count. Please try again later.",
    };
  }
}

async function create(params) {
  const transaction = await dbSAPPS.sequelize.transaction();

  try {
    // Pastikan parameter yang diperlukan ada
    if (
      !params.doc_no ||
      !params.territory_id ||
      !params.year_id ||
      !params.period_id
    ) {
      return {
        success: false,
        message:
          "Name, display name, valid from, valid to & company are required!",
      };
    }

    // periksa apakah data dengan doc_no, territory_id, year_id, period_id sudah ada di dalam database
    const existingData = await dbSAPPS.SalesPlan.findOne({
      where: {
        doc_no: params.doc_no,
        territory_id: params.territory_id,
        year_id: params.year_id,
        period_id: params.period_id,
        company_id: params.company_id,
      },
    });
    if (existingData) {
      return {
        success: false,
        message: `Sales Plan with document no ${params.doc_no} already exists.`,
      };
    }

    // periksa apakah params.callplandestinations lenght nya > 0 atau tidak
    if (params.salesplanitems.length === 0) {
      return {
        success: false,
        message: `Please select sales plan item berfore saving!`,
      };
    }

    // Jika tidak ada nilai untuk beberapa field, set default value
    if (!params.creation) params.creation = Date.now();
    if (!params.modified) params.modified = Date.now();
    if (!params.modified_by) params.modified_by = 1; // Default jika tidak ada nilai
    if (!params.owner) params.owner = 1; // Default jika tidak ada nilai

    // Buat call plan baru
    const salesPlan = await dbSAPPS.SalesPlan.create(params, { transaction });

    // Cek dan proses jika ada callplandestinations
    if (params.salesplanitems && params.salesplanitems.length > 0) {
      // Pastikan `salesplanitems` adalah array yang valid
      if (typeof params.salesplanitems === "string") {
        try {
          params.salesplanitems = JSON.parse(params.salesplanitems);
        } catch (err) {
          return {
            success: false,
            message: "Invalid JSON format for sales plan items",
          };
        }
      }

      // Pastikan bahwa `salesplanitems` adalah array yang valid dan memiliki data
      if (
        Array.isArray(params.salesplanitems) &&
        params.salesplanitems.length > 0
      ) {
        // Check unique data salesplanitems outlet_id dan client_id
        const duplicates = params.salesplanitems.filter(
          (item, index) =>
            params.salesplanitems.findIndex(
              (d) =>
                d.customer_id === item.customer_id && d.item_id === item.item_id
            ) !== index
        );
        if (duplicates.length > 0) {
          await transaction.rollback();
          return {
            success: false,
            message: `Duplicate entries exist in sales plan items for display names: ${duplicates.join(
              ", "
            )}. Transaction rolled back.`,
          };
        }

        // Persiapkan data anak untuk disimpan
        const salesPlanItemData = params.salesplanitems.map((items) => ({
          ...items,
          creation: Date.now(),
          modified: Date.now(),
          modified_by: params.modified_by || 1,
          owner: params.owner || 1,
          salesplan_id: salesPlan.id, // Assign ID dari Sales Plan yang baru saja dibuat
        }));

        // Insert data anak menggunakan bulkCreate
        await dbSAPPS.SalesPlanItem.bulkCreate(salesPlanItemData, {
          transaction,
        });
      }
    }

    // buat workflow approval
    // if (params?.workflowTerritories) {
    //     if (Array.isArray(params?.workflowTerritories) && params?.workflowTerritories.length > 0) {
    //         const workflowSettings = await dbSAPPS.WorkflowSetting.findAll({
    //             where: {
    //                 doctype_id: params.doctype_id,
    //                 type: 'Territory',
    //                 enabled: true
    //             }
    //         }, { transaction });
    //         const limitWorkflow = workflowSettings[0]?.limit || 0;
    //         const workflowTerritories = params?.workflowTerritories.slice(0, limitWorkflow);

    //         if (!workflowTerritories || workflowTerritories.length === 0) {
    //             await transaction.rollback();
    //             return {
    //                 success: false,
    //                 message: `Workflow Territories is required. Transaction rolled back.`
    //             };
    //         }

    //         const workflowData = {
    //             creation: Date.now(),
    //             modified: Date.now(),
    //             modified_by: params.modified_by || 1,
    //             owner: params.owner || 1,
    //             doctype_id: params.doctype_id,
    //             doc_id: salesPlan?.id,
    //             status: 'Draft',
    //         }

    //         const workflow = await dbSAPPS.Workflow.create(workflowData, {
    //             transaction, lock: transaction.LOCK.UPDATE
    //         });

    //         if (workflow) {
    //             const workflowApproversData = workflowTerritories?.map(workflowTerritory => ({
    //                 creation: Date.now(),
    //                 modified: Date.now(),
    //                 modified_by: params.modified_by || 1,
    //                 owner: params.owner || 1,
    //                 workflow_id: workflow.id,
    //                 territory_id: workflowTerritory?.territory_id,
    //                 status: null
    //             }));

    //             const approvers = await dbSAPPS.WorkflowApprover.bulkCreate(workflowApproversData, { transaction, lock: transaction.LOCK.UPDATE });
    //             if (approvers?.length !== workflowTerritories.length || !approvers.every(approver => approver.workflow_id === workflow.id && approver.territory_id !== null)) {
    //                 await transaction.rollback();
    //                 return {
    //                     success: false,
    //                     message: 'Failed to create workflow approvers. Please try again later.'
    //                 };
    //             }
    //         }
    //     }
    // }

    // Commit transaksi jika semua berhasil
    await transaction.commit();
    return {
      success: true,
      message: `Sales Plan has been created!`,
    };
  } catch (error) {
    // Rollback transaksi jika ada error
    await transaction.rollback();
    const errorMessage =
      error.message || `An error occurred during creating sales plan.`;
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function update(id, params) {
  const transaction = await dbSAPPS.sequelize.transaction();

  try {
    const salesPlan = await dbSAPPS.SalesPlan.findByPk(id);
    if (!salesPlan)
      return {
        success: false,
        message: "Sales Plan not found!",
      };

    // periksa apakah params.callplandestinations lenght nya > 0 atau tidak
    if (params.salesplanitems.length === 0) {
      return {
        success: false,
        message: `Please select sales plan item berfore saving!`,
      };
    }

    // Jika tidak ada nilai untuk beberapa field, set default value
    if (!params.creation) params.creation = salesPlan.creation;
    if (!params.modified) params.modified = Date.now();
    if (!params.modified_by) params.modified_by = salesPlan.modified_by || 1; // Default jika tidak ada nilai
    if (!params.owner) params.owner = salesPlan.owner || 1; // Default jika tidak ada nilai

    // Update sales plan
    const updateData = {
      ...params,
      modified: Date.now(),
      modified_by: params.modified_by || salesPlan.modified_by || 1,
    };
    const result = await salesPlan.update(updateData, { transaction });

    // Cek dan proses jika ada callplandestinations
    if (params.salesplanitems && params.salesplanitems.length > 0) {
      // Pastikan `salesplanitems` adalah array yang valid
      if (typeof params.salesplanitems === "string") {
        try {
          params.salesplanitems = JSON.parse(params.salesplanitems);
        } catch (err) {
          return {
            success: false,
            message: "Invalid JSON format for sales plan items",
          };
        }
      }

      // Pastikan bahwa `salesplanitems` adalah array yang valid dan memiliki data
      if (
        Array.isArray(params.salesplanitems) &&
        params.salesplanitems.length > 0
      ) {
        // Check unique data salesplanitems outlet_id dan client_id
        const duplicates = params.salesplanitems.filter(
          (item, index) =>
            params.salesplanitems.findIndex(
              (d) =>
                d.customer_id === item.customer_id && d.item_id === item.item_id
            ) !== index
        );
        if (duplicates.length > 0) {
          await transaction.rollback();
          return {
            success: false,
            message: `Duplicate entries exist in sales plan items for display names: ${duplicates.join(
              ", "
            )}. Transaction rolled back.`,
          };
        }

        // Persiapkan data anak untuk disimpan
        const salesPlanItemData = params.salesplanitems.map((items) => ({
          ...items,
          creation: Date.now(),
          modified: Date.now(),
          modified_by: params.modified_by || 1,
          owner: params.owner || 1,
          salesplan_id: salesPlan.id, // Assign ID dari Sales Plan yang baru saja dibuat
        }));

        // Update data anak menggunakan bulkCreate
        await dbSAPPS.SalesPlanItem.bulkCreate(salesPlanItemData, {
          updateOnDuplicate: ["modified", "modified_by", "owner"],
          transaction,
        });

        // Hapus data yang dihapus
        const deletedItems = (
          await dbSAPPS.SalesPlanItem.findAll({
            where: {
              salesplan_id: salesPlan.id,
              id: {
                [Op.notIn]: params.salesplanitems.map((d) => d.id),
              },
            },
          })
        ).map((d) => d.id);
        if (deletedItems.length > 0) {
          await dbSAPPS.SalesPlanItem.destroy({
            where: {
              id: deletedItems,
            },
            transaction,
          });
        }
      }
    }

    // Update workflow approval
    if (params?.workflowTerritories) {
      if (
        Array.isArray(params?.workflowTerritories) &&
        params?.workflowTerritories.length > 0
      ) {
        const workflowSettings = await dbSAPPS.WorkflowSetting.findAll(
          {
            where: {
              doctype_id: params.doctype_id,
              type: "Territory",
              enabled: true,
            },
          },
          { transaction }
        );
        const limitWorkflow = workflowSettings[0]?.limit || 0;
        const workflowTerritories = params?.workflowTerritories.slice(
          0,
          limitWorkflow
        );

        if (!workflowTerritories || workflowTerritories.length === 0) {
          await transaction.rollback();
          return {
            success: false,
            message: `Workflow Territories is required. Transaction rolled back.`,
          };
        }

        const workflowData = {
          creation: Date.now(),
          modified: Date.now(),
          modified_by: params.modified_by || 1,
          owner: params.owner || 1,
          doctype_id: params.doctype_id,
          doc_id: salesPlan?.id,
          status: "Draft",
        };

        const workflow = await dbSAPPS.Workflow.create(workflowData, {
          transaction,
          lock: transaction.LOCK.UPDATE,
        });

        if (workflow) {
          const workflowApproversData = workflowTerritories?.map(
            (workflowTerritory) => ({
              creation: Date.now(),
              modified: Date.now(),
              modified_by: params.modified_by || 1,
              owner: params.owner || 1,
              workflow_id: workflow.id,
              territory_id: workflowTerritory?.territory_id,
              status: null,
            })
          );

          const approvers = await dbSAPPS.WorkflowApprover.bulkCreate(
            workflowApproversData,
            { transaction, lock: transaction.LOCK.UPDATE }
          );
          if (
            approvers?.length !== workflowTerritories.length ||
            !approvers.every(
              (approver) =>
                approver.workflow_id === workflow.id &&
                approver.territory_id !== null
            )
          ) {
            await transaction.rollback();
            return {
              success: false,
              message:
                "Failed to create workflow approvers. Please try again later.",
            };
          }
        }
      }
    }

    // Commit transaksi jika semua berhasil
    await transaction.commit();
    return {
      success: true,
      message: `Sales Plan has been updated!`,
    };
  } catch (error) {
    // Rollback transaksi jika ada error
    await transaction.rollback();
    const errorMessage =
      error.message || `An error occurred during updating sales plan.`;
    return {
      success: false,
      message: errorMessage,
    };
  }
}
async function enabled(id, params) {
  try {
    const clienttype = await dbSAPPS.SalesPlan.findByPk(id);
    if (!clienttype)
      return {
        success: false,
        message: "Client Type not found!",
      };

    const updateData = {};
    updateData.enabled = params.enabled;
    if (params.modified_by) updateData.modified_by = params.modified_by;
    if (params.modified) updateData.modified = params.modified;

    await clienttype.update(updateData);

    return {
      success: true,
      message: "Client Type has been updated!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to Update Client Type.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function _delete(id) {
  try {
    const display_name = await dbSAPPS.SalesPlan.findByPk(id);
    if (!display_name)
      return { success: false, message: "Sales plan not found!" };

    await display_name.destroy();

    return {
      success: true,
      message: "Sales plan successfully deleted!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to delete Sales plan.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function generateDocumentNo(params) {
  try {
    const param = params.params;
    const documentNo = "SP-" + param.territory + "-" + param.period_name;

    const lastDocumentNo = await dbSAPPS.SalesPlan.findOne({
      where: {
        doc_no: {
          [Op.like]: `%${documentNo}%`,
        },
      },
    });

    if (lastDocumentNo) {
      throw new Error("Document No already exists!");
    }

    return {
      success: true,
      documentNo: documentNo,
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to generate document no.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function getSalesItemPlanById(id) {
  try {
    const salesItemPlan = await dbSAPPS.SalesPlanItem.findAll({
      where: {
        salesplan_id: id,
      },
    });
    if (!salesItemPlan) throw "Sales Item Plan not found, please kindly check!";
    return {
      success: true,
      salesItemPlan,
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to retrieve Sales Item Plan.";
    throw new Error(errorMessage);
  }
}

// ambil data estimasi by id dokumen sales plan
async function getEstimateByPlanId(id) {
  try {
    const salesEstimate = await dbSAPPS.SalesPlanEstimate.findAll({
      where: {
        salesplan_id: id,
        type: "estimation",
      },
      include: [
        {
          model: dbSAPPS.SalesPlan,
          as: "salesplan",
          attributes: ["id", "doc_no", "company_id", "period_id"],
          include: [
            {
              model: dbSAPPS.Period,
              as: "period",
              attributes: ["id", "display_name"],
            },
          ],
        },
        {
          model: dbSAPPS.SalesPlanItem,
          as: "salesplanitem",
          attributes: [
            "id",
            "salesplan_id",
            "customer_id",
            "item_id",
            "quantity",
            "price",
            "total_gross",
            "discount",
            "nett_price",
            "total_estimate",
            "remarks",
          ],
          include: [
            {
              model: dbSAPPS.Item,
              as: "item",
              attributes: ["id", "display_name"],
            },
            {
              model: dbSAPPS.CustomerList,
              as: "customer",
              attributes: ["id", "name"],
            },
          ],
        },
      ],
    });
    if (!salesEstimate) throw "Sales Estimate not found, please kindly check!";
    return {
      success: true,
      salesEstimate,
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to retrieve Sales Item Plan.";
    throw new Error(errorMessage);
  }
}

// generate data estimate
async function generateEstimate(params) {
  try {
    const salesPlan = await dbSAPPS.SalesPlan.findOne({
      where: {
        id: params.salesplan_id,
      },
    });
    if (!salesPlan)
      return {
        success: false,
        message: "Sales Plan not found, please kindly check!",
      };

    const existingEstimates = await dbSAPPS.SalesPlanEstimate.findAll({
      where: {
        salesplan_id: params.salesplan_id,
        type: "estimation",
      },
    });

    const salesItemPlan = await dbSAPPS.SalesPlanItem.findAll({
      where: {
        salesplan_id: params.salesplan_id,
      },
    });
    if (!salesItemPlan)
      return {
        success: false,
        message: "Sales Item Plan not found, please kindly check!",
      };

    const existingItemIds = new Set(
      existingEstimates.map((est) => est.salesplanitem_id)
    );
    const itemsToGenerate = salesItemPlan.filter(
      (item) => !existingItemIds.has(item.id)
    );

    if (itemsToGenerate.length === 0)
      return {
        success: false,
        message: "All item plans are already generated, please kindly check!",
      };

    for (let i = 0; i < itemsToGenerate.length; i++) {
      await dbSAPPS.SalesPlanEstimate.create({
        salesplan_id: params.salesplan_id,
        salesplanitem_id: itemsToGenerate[i].id,
        type: "estimation",
        created_by: params.created_by,
        creation: new Date(),
        modified_by: params.modified_by,
        modified: new Date(),
        enabled: true,
      });
    }

    return {
      success: true,
      message: "Item plans successfully generated for non-generated items!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to generate item plans.";
    throw new Error(errorMessage);
  }
}

async function updateEstimate(id, params) {
  try {
    const salesEstimate = await dbSAPPS.SalesPlanEstimate.findOne({
      where: {
        id: id,
      },
    });
    if (!salesEstimate)
      return {
        success: false,
        message: "Data not found, please kindly check!",
      };

    await dbSAPPS.SalesPlanEstimate.update(params, {
      where: {
        id: id,
      },
    });

    return {
      success: true,
      message: "Data successfully updated!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to update data.";
    throw new Error(errorMessage);
  }
}

async function deleteEstimate(id) {
  try {
    const estimate = await dbSAPPS.SalesPlanEstimate.findByPk(id);
    if (!estimate)
      return { success: false, message: "Sales plan estmiate not found!" };

    await estimate.destroy();

    return {
      success: true,
      message: "Sales plan estmiate successfully deleted!",
    };
  } catch (error) {
    const errorMessage =
      error.message || "Failed to delete Sales plan estmiate.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

// generate realization
async function generateRealization(params) {
  try {
    const salesPlan = await dbSAPPS.SalesPlan.findOne({
      where: {
        id: params.salesplan_id,
      },
    });
    if (!salesPlan)
      return {
        success: false,
        message: "Sales Plan not found, please kindly check!",
      };

    const existingEstimates = await dbSAPPS.SalesPlanEstimate.findAll({
      where: {
        salesplan_id: params.salesplan_id,
        type: "realization",
      },
    });

    const salesItemPlan = await dbSAPPS.SalesPlanItem.findAll({
      where: {
        salesplan_id: params.salesplan_id,
      },
    });
    if (!salesItemPlan)
      return {
        success: false,
        message: "Sales Item Plan not found, please kindly check!",
      };

    const existingItemIds = new Set(
      existingEstimates.map((est) => est.salesplanitem_id)
    );
    const itemsToGenerate = salesItemPlan.filter(
      (item) => !existingItemIds.has(item.id)
    );

    if (itemsToGenerate.length === 0)
      return {
        success: false,
        message: "All item plans are already generated, please kindly check!",
      };

    for (let i = 0; i < itemsToGenerate.length; i++) {
      await dbSAPPS.SalesPlanEstimate.create({
        salesplan_id: params.salesplan_id,
        salesplanitem_id: itemsToGenerate[i].id,
        type: "realization",
        created_by: params.created_by,
        creation: new Date(),
        modified_by: params.modified_by,
        modified: new Date(),
        enabled: true,
      });
    }

    return {
      success: true,
      message: "Item plans successfully generated for non-generated items!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to generate item plans.";
    throw new Error(errorMessage);
  }
}

async function getRealizationByPlanId(id) {
  try {
    const salesRealization = await dbSAPPS.SalesPlanEstimate.findAll({
      where: {
        salesplan_id: id,
        type: "realization",
      },
      include: [
        {
          model: dbSAPPS.SalesPlan,
          as: "salesplan",
          attributes: ["id", "doc_no", "company_id", "period_id"],
          include: [
            {
              model: dbSAPPS.Period,
              as: "period",
              attributes: ["id", "display_name"],
            },
          ],
        },
        {
          model: dbSAPPS.SalesPlanItem,
          as: "salesplanitem",
          attributes: [
            "id",
            "salesplan_id",
            "customer_id",
            "item_id",
            "quantity",
            "price",
            "total_gross",
            "discount",
            "nett_price",
            "total_estimate",
            "remarks",
          ],
          include: [
            {
              model: dbSAPPS.Item,
              as: "item",
              attributes: ["id", "display_name"],
            },
            {
              model: dbSAPPS.CustomerList,
              as: "customer",
              attributes: ["id", "name"],
            },
          ],
        },
      ],
    });
    if (!salesRealization)
      throw "Sales Realization not found, please kindly check!";
    return {
      success: true,
      salesRealization,
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to retrieve Sales Item Plan.";
    throw new Error(errorMessage);
  }
}
