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 clientSubtypes = await dbSAPPS.ClientSubtype.findAll({
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.ClientType,
          as: "clienttype",
        },
      ],
    });

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

async function filter(params) {
  const filterConditions = {};

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

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

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

  if (params.enabled) {
    filterConditions.enabled = {
      [Op.eq]: params.enabled === "1" ? true : false,
    };
  }

  try {
    const clientSubtypes = await dbSAPPS.ClientSubtype.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.ClientType,
          as: "clienttype",
          attributes: ["id", "display_name"],
        },
      ],
    });

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

async function option() {
  try {
    const clientSubtypes = await dbSAPPS.ClientSubtype.findAll({
      attributes: ["id", "display_name", "code"],
      where: { enabled: true },
      order: [["display_name", "ASC"]],
      include: [
        {
          model: dbSAPPS.ClientType,
          as: "clienttype",
          attributes: ["id", "display_name"],
        },
      ],
    });

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

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

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

async function create(params) {
  try {
    if (!params.clienttype_id)
      return {
        success: false,
        message: "Client type is required!",
      };

    if (!params.display_name)
      return {
        success: false,
        message: "Client Sub type is required!",
      };

    const existingClientSubtype = await dbSAPPS.ClientSubtype.findOne({
      where: {
        clienttype_id: params.clienttype_id,
        display_name: params.display_name,
        code: params.code,
      },
    });

    if (existingClientSubtype)
      return {
        success: false,
        message: `Client Subtype of "${params.display_name}" is already taken.`,
      };

    if (!params.enabled) params.enabled = true;
    const newClientSubtype = await dbSAPPS.ClientSubtype.create(params);

    return {
      success: true,
      message: "Data Client Subtype has been successfully adeded!",
      clientSubtypes: newClientSubtype,
    };
  } catch (error) {
    const errorMessage =
      error.message || "An error occurred during Client Subtype  creation.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

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

    if (
      params.display_name &&
      params.display_name !== clientSubtype.display_name &&
      params.clienttype_id &&
      params.clienttype_id !== clientSubtype.clienttype_id
    ) {
      const existingClientTypeName = await dbSAPPS.ClientSubtype.findOne({
        where: {
          display_name: params.display_name,
          clienttype_id: params.clienttype_id,
          code: params.code,
        },
      });
      if (existingClientTypeName) {
        return {
          success: false,
          message: `Client sub type of "${params.display_name}" is already taken. Try again!`,
        };
      }
    }

    await clientSubtype.update(params);

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

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

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

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

    await display_name.destroy();

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

