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 {
    // Mengambil semua pengguna dan mengurutkannya berdasarkan kolom 'modified' secara menurun
    const itemGroups = await dbSAPPS.ItemGroup.findAll({
      order: [["modified", "DESC"]],
      include: [
        {
          model : dbSAPPS.Company,
          as : "company",
          attributes:["id","display_name"]
        }
      ],
    });

    // Mengembalikan respons dengan status 200 OK
    return {
      itemGroups,
      success: true,
      message: "Item groups loaded successfully!",
    };
  } catch (error) {
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    const errorMessage = error.message || "Failed to load Item groups!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function filter(params) {
  // Membuat objek filter dengan validasi
  const filterConditions = {};

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

  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 {
    // Mencari pengguna berdasarkan filter conditions
    const itemGroups = await dbSAPPS.ItemGroup.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]], // Opsional: Mengurutkan hasil berdasarkan kolom 'modified'
      include: [
        {
          model : dbSAPPS.Company,
          as : "company",
          attributes:["id","display_name"]
        }
      ],
    });

    // Mengembalikan hasil pencarian
    return {
      success: true,
      itemGroups,
      message: "Item groups loaded successfully!",
    };
  } catch (error) {
    // Logging error untuk keperluan debugging
    console.error("Error retrieving Item groups: ", error);
    const errorMessage =
      error.message ||
      "Failed to retrieve Item groups. Please try again later.";
    // Mengembalikan respons dengan status 500 Internal Server Error
    return {
      success: false,
      message: errorMessage,
    };
  }
}

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

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

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

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

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

    const existingItemGroupName = await dbSAPPS.ItemGroup.findOne({
      where: {
        display_name: params.display_name,
        company_id: params.company_id,
      },
    });

    if (existingItemGroupName)
      return {
        success: false,
        message: `Item Group "${params.display_name}" with same company  is already taken.`,
      };

    if (!params.enabled) params.enabled = true;
    const newItemGroup = await dbSAPPS.ItemGroup.create(params);

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

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

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

    await itemGroups.update(params);

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

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

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

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

    await itemGroups.destroy();

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