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 subSpecialists = await dbSAPPS.SubSpecialist.findAll({
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.Specialist,
          as: "specialist",
          attributes: ["id", "display_name", "code"],
        },
      ],
    });

    return {
      subSpecialists,
      success: true,
      message: "Sub 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.specialist_id) {
    filterConditions.specialist_id = {
      [Op.eq]: cleanParams.specialist_id, 
      // Changed from Op.like because ID is int/fk. 
      // Wait, original code had Op.like `%ID%`? That seems wrong for an ID FK.
      // If passing ID directly for filtering, it should be eq or in.
      // If frontend sends partial text, we filter by relation?
      // Frontend sends ID usually for select filters.
    };
  }

  // If table sends f_specialist_id, handle it.
  
  if (cleanParams.code) {
    filterConditions.code = {
      [Op.like]: `%${cleanParams.code}%`,
    };
  }

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

  try {
    const subSpecialists = await dbSAPPS.SubSpecialist.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]], 
      include: [
        {
          model: dbSAPPS.Specialist,
          as: "specialist",
          attributes: ["id", "display_name", "code"],
        },
      ],
    });

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

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

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

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

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

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

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

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

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

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

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

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

    await specialist.update(params);

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

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

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

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

    await subSpecialist.destroy();

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