const { Op } = require("sequelize");
const dbSAPPS = require("../../helpers/db");
require("dotenv").config();

module.exports = {
  getAll,
  option,
  count,
  create,
  update,
  enabled,
  filter,
  delete: _delete,
};

const formatWithModifier = async (travelCostRates) => {
  return Promise.all(
    travelCostRates.map(async (rc) => {
      const modifier = await dbSAPPS.User.findOne({
        where: {
          id: rc.modified_by,
        },
        attributes: ["full_name"],
      });

      return {
        ...rc,
        modifier: modifier?.full_name,
      };
    })
  );
};

async function getAll(params) {
  try {
    const filterConditions = {};
    let travelCostRates = [];
    travelCostRates = await dbSAPPS.TravelCostRate.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.Company,
          as: "company",
          attributes: ["id", "display_name"],
        },
        {
          model: dbSAPPS.Designation,
          as: "designation",
          attributes: ["id", "display_name"],
        },
      ],
    });

    travelCostRates = travelCostRates.map((rc) => {
      return {
        ...rc.dataValues,
        company_name: rc?.company?.display_name || null,
        designation_name: rc?.designation?.display_name || null,
      };
    });

    travelCostRates = await formatWithModifier(travelCostRates);

    // Mengembalikan respons dengan status 200 OK
    return {
      travelCostRates,
      success: true,
      message: "travelCostRates loaded successfully!",
    };
  } catch (error) {
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    const errorMessage = error.message || "Failed to load travelCostRates!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function filter(params) {
  // Membuat objek filter dengan validasi
  const filterConditions = {};

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

  if (params.designation_id) {
    filterConditions.designation_id = {
      [Op.eq]: params.designation_id,
    };
  }

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

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

  try {
    // Mencari pengguna berdasarkan filter conditions
    const travelCostRates = await dbSAPPS.TravelCostRate.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]], // Opsional: Mengurutkan hasil berdasarkan kolom 'modified'
      include: [
        {
          model: dbSAPPS.Company,
          as: "company",
          attributes: ["id", "display_name"],
        },
        {
          model: dbSAPPS.Designation,
          as: "designation",
          attributes: ["id", "display_name"],
        },
      ],
    });

    // Mengembalikan hasil pencarian
    return {
      success: true,
      travelCostRates,
      message: "Travel Cost Rate loaded successfully!",
    };
  } catch (error) {
    // Logging error untuk keperluan debugging
    console.error("Error retrieving Travel Cost Rate: ", error);
    const errorMessage = error.message || "Failed to retrieve Travel Cost Rate. Please try again later.";
    // Mengembalikan respons dengan status 500 Internal Server Error
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function option() {
  try {
    // Mencari pengguna yang diaktifkan dengan atribut tertentu
    const travelCostRates = await dbSAPPS.TravelCostRate.findAll({
      attributes: [
        "id",
        "designation_id",
        "company_id",
        "accomodation_rate",
        "daily_meal_rate",
        "daily_operational_rate",
        "group_meal_rate",
        "effective_date",
        "expiry_date",
      ],
      where: { enabled: true },
      order: [["designation_id", "ASC"]], // Opsional: Mengurutkan hasil berdasarkan
    });

    // Mengembalikan hasil pencarian
    return {
      success: true,
      travelCostRates,
      message: "Travel Cost Rate loaded successfully!",
    };
  } catch (error) {
    // Logging error untuk keperluan debugging
    console.error("Error retrieving Travel Cost Rate: ", error);
    const errorMessage = error.message || "Failed to retrieve Travel Cost Rate. Please try again later.";
    // Mengembalikan respons dengan status 500 Internal Server Error
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function count() {
  try {
    // Menghitung jumlah pengguna yang diaktifkan
    const count = await dbSAPPS.TravelCostRate.count({
      where: { enabled: true },
    });

    // Mengembalikan hasil hitung
    return {
      success: true,
      count,
      message: "travelCostRates loaded successfully!",
    };
  } catch (error) {
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    console.error("Error counting Travel Cost Rate: ", error);
    return {
      success: false,
      message: "Failed to retrieve Travel Cost Rate count. Please try again later.",
    };
  }
}

async function create(params) {
  try {
    // Create data
    await dbSAPPS.TravelCostRate.create(params);

    // Respons sukses
    return {
      success: true,
      message: "Travel Cost Rate has been successfully created!",
    };
  } catch (error) {
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    const errorMessage = error.message || "An error occurred during travel cost rate created.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function update(id, params) {
  try {
    // Temukan  berdasarkan id
    const travelCostRate = await dbSAPPS.TravelCostRate.findByPk(id);
    if (!travelCostRate) {
      return {
        success: false,
        message: "Travel Cost Rate not found!",
      };
    }

    // Update data
    await travelCostRate.update(params);

    // Respons sukses
    return {
      success: true,
      message: "Travel Cost Rate has been successfully updated!",
      travelCostRate,
    };
  } catch (error) {
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    const errorMessage = error.message || "An error occurred during travel cost rate update.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

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

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

async function _delete(id) {
  try {
    // Mengambil pengguna dari database
    const travelCostRate = await dbSAPPS.TravelCostRate.findByPk(id);
    if (!travelCostRate) return { success: false, message: "travel cost rate not found!" };

    // Menghapus pengguna dari database
    await travelCostRate.destroy();

    // Respons sukses
    return {
      success: true,
      message: "travel cost rate successfully deleted!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to delete travel cost rate.";
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    return {
      success: false,
      message: errorMessage,
    };
  }
}
