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 years = await dbSAPPS.Year.findAll({
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.Period,
          as: "periods",
          attributes: ["id", "display_name", "start_date", "end_date"],
        },
      ],
    });

    return {
      years,
      success: true,
      message: "years loaded successfully!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to load years!";
    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}%` } },
    ];
  }

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

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

  try {
    const years = await dbSAPPS.Year.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.Period,
          as: "periods",
          attributes: ["id", "display_name", "start_date", "end_date"],
        },
      ],
    });

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

async function option() {
  try {
    const years = await dbSAPPS.Year.findAll({
      attributes: ["id", "display_name"],
      where: { enabled: true },
      order: [["display_name", "ASC"]],
      include: [
        {
          model: dbSAPPS.Period,
          as: "periods",
          attributes: ["id", "display_name", "start_date", "end_date"],
        },
      ],
    });

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

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

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

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

    const existingYear = await dbSAPPS.Year.findOne({
      where: {
        display_name: params.display_name,
      },
    });
    if (existingYear)
      return {
        success: false,
        message: `Year of "${params.display_name}" is already taken.`,
      };

    if (!params.enabled) params.enabled = true;
    const newYear = await dbSAPPS.Year.create(params);

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

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

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

    await year.update(params);

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

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

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

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

    await year.destroy();

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