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

module.exports = {
  getAll,
  filter,
  option,
  count,
  create,
  update,
  enabled,
  delete: _delete,
};

async function getAll() {
  try {
    const itemCompetitors = await dbSAPPS.ItemCompetitor.findAll({
      order: [["modified", "DESC"]],
      include: [{ model: dbSAPPS.Item, as: "item", attributes: ["id", "display_name"] }],
    });

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

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

  if (params.display_name) {
    filterConditions.display_name = {
      [Op.like]: `%${params.display_name}%`,
    };
  }

  if (params.item_id) {
    filterConditions.item_id = {
      [Op.like]: `%${params.item_id}%`,
    };
  }

  if (params.enabled) {
    filterConditions.enabled = {
      [Op.eq]: params.enabled === "1" ? true : false,
    };
  }
  try {
    const itemCompetitors = await dbSAPPS.ItemCompetitor.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]],
    });

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

async function option() {
  try {
    const itemCompetitors = await dbSAPPS.ItemCompetitor.findAll({
      attributes: ["id", "display_name"],
      where: { enabled: true },
      order: [["display_name", "ASC"]],
      include: [{ model: dbSAPPS.Item, as: "item", attributes: ["id", "display_name"] }],
    });

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

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

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

async function create(params) {
  try {
    if (!params.display_name || !params.item_id)
      return {
        success: false,
        message: "Item Competitor name and Item  are required!",
      };

    const existingNameNNumber = await dbSAPPS.ItemCompetitor.findOne({
      where: {
        display_name: params.display_name,
        item_id: params.item_id,
      },
    });
    if (existingNameNNumber)
      return {
        success: false,
        message: `Item Competitor name "${params.display_name}" and item "${params.item_id}" is already taken.`,
      };

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

    const newitemCompetitors = await dbSAPPS.ItemCompetitor.create(params);

    return {
      success: true,
      message: "Item Competitor data has been successfully added!",
      itemCompetitors: newitemCompetitors,
    };
  } catch (error) {
    const errorMessage =
      error.message ||
      "An error occurred during create Item Competitors processing.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function update(id, params) {
  try {
    const itemCompetitors = await dbSAPPS.ItemCompetitor.findByPk(id);
    if (!itemCompetitors)
      return {
        success: false,
        message: "Item Competitor not found!",
      };

    if (
      params.display_name &&
      params.display_name !== itemCompetitors.display_name &&
      params.item_id &&
      params.item_id !== itemCompetitors.item_id
    ) {
      const existingitemCompetitorsName = await dbSAPPS.ItemCompetitor.findOne({
        where: { display_name: params.display_name, item_id: params.item_id },
      });
      if (existingitemCompetitorsName) {
        return {
          success: false,
          message: `Item Competitor name "${params.display_name}" is already taken. Try again!`,
        };
      }
    }

    await itemCompetitors.update(params);

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

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

    return {
      success: true,
      message: "Item Competitor has been updated!",
    };
  } catch (error) {
    const errorMessage =
      error.message || "Failed to update Item CompetitorGroups.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function _delete(id) {
  try {
    const itemCompetitors = await dbSAPPS.ItemCompetitor.findByPk(id);
    if (!itemCompetitors)
      return { success: false, message: "Item Competitor not found!" };

    await itemCompetitors.destroy();

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