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

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

async function getAll(params) {
  try {
    const filterConditions = {};
    const andConditions = [];
    const safeParams = params && typeof params === "object" ? params : {};

    if (safeParams.enabled !== undefined && safeParams.enabled !== "") {
      filterConditions.enabled = safeParams.enabled === "1" || safeParams.enabled === true;
    }

    if (safeParams.q && String(safeParams.q).trim().length > 0) {
      const q = String(safeParams.q).trim();
      andConditions.push({
        [Op.or]: [
          { name: { [Op.like]: `%${q}%` } },
          { contact: { [Op.like]: `%${q}%` } },
          { notes: { [Op.like]: `%${q}%` } },
        ],
      });
    }

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

    const list = await dbSAPPS.DeliveryExpeditionVendor.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]],
    });

    const data = list.map((row) => row.dataValues);

    return {
      data,
      success: true,
      message: "Loaded successfully!",
    };
  } catch (error) {
    const errorMessage = error?.message || "Failed to load, please try again!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function option(params) {
  try {
    const filterConditions = { enabled: true };

    const list = await dbSAPPS.DeliveryExpeditionVendor.findAll({
      where: filterConditions,
      attributes: ["id", "name", "contact"],
      order: [["name", "ASC"]],
    });

    const options = list.map((row) => ({
      id: row.id,
      name: row.name,
      contact: row.contact,
      display_name: row.name,
    }));

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

async function count(params) {
  try {
    const filterConditions = {};
    if (params?.enabled !== undefined && params.enabled !== "") {
      filterConditions.enabled = params.enabled === "1" || params.enabled === true;
    }
    const total = await dbSAPPS.DeliveryExpeditionVendor.count({
      where: filterConditions,
    });
    return {
      count: total,
      success: true,
      message: "Count loaded successfully!",
    };
  } catch (error) {
    return {
      success: false,
      message: error?.message || "Failed to count!",
    };
  }
}

async function create(params) {
  const transaction = await dbSAPPS.sequelize.transaction();
  try {
    const existing = await dbSAPPS.DeliveryExpeditionVendor.findOne({
      where: { name: params.name },
      transaction,
    });
    if (existing) {
      await transaction.rollback();
      return { success: false, message: `"${params.name}" is already taken.` };
    }

    await dbSAPPS.DeliveryExpeditionVendor.create(params, { transaction });
    await transaction.commit();
    return { success: true, message: "Saved successfully!" };
  } catch (error) {
    await transaction.rollback();
    return {
      success: false,
      message: error?.message || "Failed to save!",
    };
  }
}

async function update(id, params) {
  const transaction = await dbSAPPS.sequelize.transaction();
  try {
    const row = await dbSAPPS.DeliveryExpeditionVendor.findByPk(id);
    if (!row) {
      await transaction.rollback();
      return { success: false, message: "ID not found!" };
    }

    if (params.name) {
      const existing = await dbSAPPS.DeliveryExpeditionVendor.findOne({
        where: { name: params.name, id: { [Op.ne]: id } },
        transaction,
      });
      if (existing) {
        await transaction.rollback();
        return { success: false, message: `"${params.name}" is already taken.` };
      }
    }

    await row.update(params, { transaction });
    await transaction.commit();
    return { success: true, message: "Saved successfully!" };
  } catch (error) {
    await transaction.rollback();
    return {
      success: false,
      message: error?.message || "Failed to save!",
    };
  }
}

async function enabled(id, params) {
  const transaction = await dbSAPPS.sequelize.transaction();
  try {
    const row = await dbSAPPS.DeliveryExpeditionVendor.findByPk(id);
    if (!row) {
      await transaction.rollback();
      return { success: false, message: "ID not found!" };
    }
    const updateData = { enabled: params.enabled };
    if (params.modified_by != null) updateData.modified_by = params.modified_by;
    if (params.modified != null) updateData.modified = params.modified;
    await row.update(updateData, { transaction });
    await transaction.commit();
    return { success: true, message: "Saved successfully!" };
  } catch (error) {
    await transaction.rollback();
    return {
      success: false,
      message: error?.message || "Failed to save!",
    };
  }
}

async function _delete(id) {
  const transaction = await dbSAPPS.sequelize.transaction();
  try {
    const row = await dbSAPPS.DeliveryExpeditionVendor.findByPk(id, { transaction });
    if (!row) {
      await transaction.rollback();
      return { success: false, message: "ID not found!" };
    }
    await row.destroy({ transaction });
    await transaction.commit();
    return { success: true, message: "Deleted successfully!" };
  } catch (error) {
    await transaction.rollback();
    return {
      success: false,
      message: error?.message || "Failed to delete!",
    };
  }
}
