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

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

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

  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 specialists = await dbSAPPS.Specialist.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.ClientType,
          as: "clienttype",
        },
        {
          model: dbSAPPS.SubSpecialist,
          as: "subspecialists",
        },
      ],
    });

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

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

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

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

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

async function create(params) {
  try {
    if (!params.display_name)
      return {
        success: false,
        message: "Specialist name is required!",
      };

    const existingSpecialist = await dbSAPPS.Specialist.findOne({
      where: {
        clienttype_id: params.clienttype_id,
        display_name: params.display_name,
      },
    });

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

    if (!params.enabled) params.enabled = true;
    const newSpecialist = await dbSAPPS.Specialist.create(params);

    return {
      success: true,
      message: "Data Specialist has been successfully added!",
      specialists: newSpecialist,
    };
  } catch (error) {
    const errorMessage =
      error.message || "An error occurred during Specialist creation.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

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

    if (
      params.display_name &&
      params.display_name !== specialist.display_name &&
      params.clienttype_id &&
      params.clienttype_id !== specialist.clienttype_id
    ) {
      const existingDisplayName = await dbSAPPS.Specialist.findOne({
        where: {
          display_name: params.display_name,
          clienttype_id: params.clienttype_id,
        },
      });
      if (existingDisplayName) {
        return {
          success: false,
          message: `Specialist of "${params.display_name}" is already taken. Try again!`,
        };
      }
    }

    await specialist.update(params);

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

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

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

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

    await specialist.destroy();

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