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) {
  try {
    const { 
      limit, 
      offset, 
      page, 
      q, 
      companiesId,
      company_id,
      ...otherParams 
    } = params;

    const queryLimit = limit ? parseInt(limit) : 10;
    const queryOffset = offset ? parseInt(offset) : (page ? (parseInt(page) - 1) * queryLimit : 0);

    const whereConditions = {};
    const andConditions = [];

    // Global Search (q)
    if (q) {
      andConditions.push({
        [Op.or]: [
          { display_name: { [Op.iLike]: `%${q}%` } },
          { code: { [Op.iLike]: `%${q}%` } },
        ]
      });
    }

    // Standard Filters
    if (params.display_name) {
        andConditions.push({ display_name: { [Op.iLike]: `%${params.display_name}%` } });
    }
    
    if (params.code) {
        andConditions.push({ code: { [Op.iLike]: `%${params.code}%` } });
    }

    // Handle company_id
    if (company_id) {
         andConditions.push({ company_id: company_id });
    } else if (companiesId) {
         // If companiesId is passed as array or list
         if (Array.isArray(companiesId)) {
             andConditions.push({ company_id: { [Op.in]: companiesId } });
         } else {
             // If string comma separated
             const ids = String(companiesId).split(',').map(id => id.trim());
             if (ids.length > 0) {
                 andConditions.push({ company_id: { [Op.in]: ids } });
             }
         }
    }

    // Handle f_ filters (for column filters from MRT)
    Object.keys(otherParams).forEach(key => {
        if (key.startsWith('f_')) {
            const field = key.substring(2);
            let value = otherParams[key];
            if (value !== undefined && value !== null && value !== '') {
               if (field === 'enabled') {
                   const isEnabled = value === 'true' || value === '1';
                   andConditions.push({ [field]: isEnabled });
               } else if (field === 'id' || field.endsWith('_id')) {
                    andConditions.push({ [field]: value });
               } else {
                    andConditions.push({ [field]: { [Op.iLike]: `%${value}%` } });
               }
            }
        }
    });

    if (params.enabled !== undefined) {
         const isEnabled = params.enabled === '1' || params.enabled === 'true' || params.enabled === true;
         andConditions.push({ enabled: isEnabled });
    }

    if (andConditions.length > 0) {
      whereConditions[Op.and] = andConditions;
    }

    const { count, rows } = await dbSAPPS.ItemGroup.findAndCountAll({
      where: whereConditions,
      limit: queryLimit,
      offset: queryOffset,
      order: [["modified", "DESC"]],
      include: [
        {
          model : dbSAPPS.Company,
          as : "company",
          attributes:["id","display_name"]
        }
        // Add territories if needed for display? Probably not for list view.
      ],
      distinct: true,
    });

    return {
      success: true,
      itemGroups: rows,
      total: count,
      message: "Item groups loaded successfully!",
    };
  } catch (error) {
    console.error("Error retrieving Item groups: ", error);
    const errorMessage = error.message || "Failed to retrieve Item groups.";
    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,
    };
  }
}
