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) {
  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 itemWhereConditions = {};
    const andConditions = [];

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

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

    // Company Filter (Applied to Item)
    if (company_id) {
         itemWhereConditions.company_id = company_id;
    } else if (companiesId) {
         if (Array.isArray(companiesId)) {
             itemWhereConditions.company_id = { [Op.in]: companiesId };
         } else {
             const ids = String(companiesId).split(',').map(id => id.trim());
             if (ids.length > 0) {
                 itemWhereConditions.company_id = { [Op.in]: ids };
             }
         }
    }

    // f_ filters
    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 === 'item_display_name') {
                    andConditions.push({ '$item.display_name$': { [Op.iLike]: `%${value}%` } });
               } else if (field === 'company_display_name') {
                    andConditions.push({ '$item.company.display_name$': { [Op.iLike]: `%${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.ItemCompetitor.findAndCountAll({
      where: whereConditions,
      limit: queryLimit,
      offset: queryOffset,
      order: [["modified", "DESC"]],
      include: [
        { 
            model: dbSAPPS.Item, 
            as: "item", 
            attributes: ["id", "display_name", "code", "company_id"],
            where: Object.keys(itemWhereConditions).length > 0 ? itemWhereConditions : undefined,
            include: [
                {
                    model: dbSAPPS.Company,
                    as: "company",
                    attributes: ["id", "display_name"]
                }
            ]
        }
      ],
      distinct: true,
      subQuery: false // Important when using limit with includes and where clauses on includes
    });

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