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 items = await dbSAPPS.Item.findAll({
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.Company,
          as: "company",
          attributes: ["id", "display_name"],
        },
        {
          model: dbSAPPS.ItemGroup,
          as: "itemgroups",
          attributes: ["id", "display_name"],
        },
        {
          model: dbSAPPS.ItemCompetitor,
          as: "itemcompetitors",
          attributes: ["id", "display_name", "item_id"],
        },
      ],
    });

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

async function filter(params) {
  console.log("params : ", params);
  const filterConditions = {};

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

  if (params.itemgroups) {
    filterConditions.itemgroup_id = {
      [Op.in]: params.itemgroups,
    };
  }

  if (params.itemgroup_id) {
    filterConditions.itemgroup_id = {
      [Op.eq]: params.itemgroup_id,
    };
  }

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

  if (params.enabled) {
    filterConditions.enabled = {
      [Op.eq]: params.enabled === "1" ? true : false,
    };
  }
  try {
    const items = await dbSAPPS.Item.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.Company,
          as: "company",
          attributes: ["id", "display_name"],
        },
        {
          model: dbSAPPS.ItemGroup,
          as: "itemgroups",
          attributes: ["id", "display_name"],
        },
      ],
    });

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

async function option() {
  try {
    const items = await dbSAPPS.Item.findAll({
      attributes: [
        "id",
        "display_name",
        "item_cor",
        "itemgroup_id",
        "code",
        "company_id",
        "sku_code",
        "alternative_sku_code",
        "price",
        "stock_uom",
        "valid_from",
        "standard_rate",
      ],
      where: { enabled: true },
      order: [["display_name", "ASC"]],
    });

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

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

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

async function create(params) {
  try {
    if (!params.display_name)
      return {
        success: false,
        message: "items name is required!",
      };

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

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

    const newitems = await dbSAPPS.Item.create(params);

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

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

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

    await items.update(params);

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

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

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

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

    await items.destroy();

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