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",
        },
      ],
    });

    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 = {};
  
  // Handle 'f_' prefix from frontend table filters
  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.display_name) {
    filterConditions.display_name = {
      [Op.like]: `%${cleanParams.display_name}%`,
    };
  }

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

  if (cleanParams.enabled) {
    filterConditions.enabled = {
      [Op.eq]: cleanParams.enabled === "1" ? true : false,
    };
  }
  
  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;
  }

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

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

    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,
    };
  }
}
