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

module.exports = {
  getAll,
  option,
  count,
  create,
  update,
  enabled,
  delete: _delete,
};
const formatWithModifier = async (tenderCategories) => {
  return Promise.all(
    tenderCategories.map(async (tenderCategory) => {
      const modifier = await dbSAPPS.User.findOne({
        where: {
          id: tenderCategory.modified_by,
        },
        attributes: ["full_name"],
      });

      return {
        ...tenderCategory,
        modifier: modifier?.full_name,
      };
    })
  );
};

async function getAll(params) {
  try {
    // filter
    const filterConditions = {};
    let tenderCategories = [];
    tenderCategories = await dbSAPPS.TenderCategory.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]],
    });

    tenderCategories = tenderCategories.map((tenderCategory) => {
      return {
        ...tenderCategory.dataValues
      };
    });

    tenderCategories = await formatWithModifier(tenderCategories);

    return {
      tenderCategories,
      success: true,
      message: "Tender categories loaded successfully!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to load tender categories!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function option(params) {
  try {
    const tenderCategories = await dbSAPPS.TenderCategory.findAll({
      attributes: ["id", "display_name", "code"],
      where: { enabled: true },
      order: [["display_name", "ASC"]],
    });

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

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

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

async function create(params) {
  const transaction = await dbSAPPS.sequelize.transaction();
  try {
    // validate existing
    const existingDisplayName = await dbSAPPS.TenderCategory.findOne({
      where: { display_name: params.display_name },
      transaction,
    });
    if (existingDisplayName) {
      return {
        success: false,
        message: `"${params.display_name}" is already taken.`,
      };
    }


    if (!params.enabled) params.enabled = true;

    // save
    await dbSAPPS.TenderCategory.create(params, { transaction });

    await transaction.commit();
    return {
      success: true,
      message: "Saved successfully!",
    };
  } catch (error) {
    await transaction.rollback();
    const errorMessage = error?.message || "Failed to save, please try again!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function update(id, params) {
  try {
    const tenderCategory = await dbSAPPS.TenderCategory.findByPk(id);
    if (!tenderCategory)
      return {
        success: false,
        message: "Tender Category not found!",
      };

    if (params.display_name && params.display_name !== tenderCategory.display_name) {
      const existingTenderCategoryName = await dbSAPPS.TenderCategory.findOne({
        where: { display_name: params.display_name },
      });
      if (existingTenderCategoryName) {
        return {
          success: false,
          message: `Tender Category name "${params.display_name}" is already taken. Try again!`,
        };
      }
    }

    await tenderCategory.update(params);

    return {
      success: true,
      message: "Data tender category has been saved!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to update tender category data.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function enabled(id, params) {
  try {
    const tenderCategory = await dbSAPPS.TenderCategory.findByPk(id);
    if (!tenderCategory)
      return {
        success: false,
        message: "Tender Category 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 tenderCategory.update(updateData);

    return {
      success: true,
      message: "Tender Category has been updated!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to update tender category.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function _delete(id) {
  try {
    const tenderCategory = await dbSAPPS.TenderCategory.findByPk(id);
    if (!tenderCategory) return { success: false, message: "Tender Category not found!" };

    await tenderCategory.destroy();

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