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 = {};
  const cleanParams = { ...params };
  Object.keys(cleanParams).forEach((key) => {
    if (key.startsWith("f_")) {
      cleanParams[key.substring(2)] = cleanParams[key];
    }
  });

  if (cleanParams.q) {
    filterConditions[Op.or] = [
      { display_name: { [Op.like]: `%${cleanParams.q}%` } },
      { code: { [Op.like]: `%${cleanParams.q}%` } },
    ];
  }
  if (cleanParams.clientTypesId && Array.isArray(cleanParams.clientTypesId) && cleanParams.clientTypesId.length > 0) {
    filterConditions.clienttype_id = { [Op.in]: cleanParams.clientTypesId };
  } else if (cleanParams.clienttype_id != null && cleanParams.clienttype_id !== "") {
    const id = parseInt(cleanParams.clienttype_id, 10);
    if (!Number.isNaN(id)) filterConditions.clienttype_id = id;
  }
  if (cleanParams.display_name) {
    filterConditions.display_name = { [Op.like]: `%${cleanParams.display_name}%` };
  }
  if (cleanParams.code) {
    filterConditions.code = { [Op.like]: `%${cleanParams.code}%` };
  }
  if (cleanParams.enabled !== undefined && cleanParams.enabled !== null && cleanParams.enabled !== "") {
    filterConditions.enabled = cleanParams.enabled === "1" || cleanParams.enabled === true;
  }

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

    const clientSubtypes = rows.map((row) => {
      const plain = row.get ? row.get({ plain: true }) : row;
      return { ...plain, modifier: plain.modifier?.full_name ?? null };
    });

    return {
      success: true,
      clientSubtypes,
      message: "Client Sub 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,
    };
  }
}

