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

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

const formatWithModifier = async (regCategories) => {
  return Promise.all(
    regCategories.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 regCategories = [];
     regCategories = await dbSAPPS.RegCategories.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.Company,
          as: "company",
          attributes: ["id", "display_name"],
        },
      ],
    });

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

    regCategories = await formatWithModifier(regCategories);

    // Mengembalikan respons dengan status 200 OK
    return {
      regCategories,
      success: true,
      message: "regCategories loaded successfully!",
    };
  } catch (error) {
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    const errorMessage = error.message || "Failed to load regCategories!";
    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.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 regCategories = await dbSAPPS.RegCategories.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]], // Opsional: Mengurutkan hasil berdasarkan kolom 'modified'
      include: [
        {
          model: dbSAPPS.Company,
          as: "company",
          attributes: ["id", "display_name"],
        },
      ],
    });

    // Mengembalikan hasil pencarian
    return {
      success: true,
      regCategories,
      message: "Reg Categories loaded successfully!",
    };
  } catch (error) {
    // Logging error untuk keperluan debugging
    console.error("Error retrieving Reg Categories: ", error);
    const errorMessage =
      error.message || "Failed to retrieve Reg Categories. 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 regCategories = await dbSAPPS.RegCategories.findAll({
      attributes: ["id", "display_name"],
      where: { enabled: true },
      order: [["display_name", "ASC"]], // Opsional: Mengurutkan hasil berdasarkan
    });

    // Mengembalikan hasil pencarian
    return {
      success: true,
      regCategories,
      message: "Reg Categories loaded successfully!",
    };
  } catch (error) {
    // Logging error untuk keperluan debugging
    console.error("Error retrieving Reg Categories: ", error);
    const errorMessage =
      error.message || "Failed to retrieve Reg Categories. 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.RegCategories.count({
      where: { enabled: true },
    });

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

async function create(params) {
  try {
    // Validasi input
    if (!params.display_name || !params.company_id) {
      return {
        success: false,
        message: "Reg Category name and Company are required!",
      };
    }

    // Periksa apakah nama atau kode baru sudah digunakan
    const existingNameNNumber = await dbSAPPS.RegCategories.findOne({
      where: {
        display_name: params.display_name,
        company_id: params.company_id,
      },
    });
    if (existingNameNNumber) {
      return {
        success: false,
        message: `Name "${params.display_name}" and company "${params.company_id}" is already taken.`,
      };
    }

    // Create data kategori regulasi
    await dbSAPPS.RegCategories.create(params);

    // Respons sukses
    return {
      success: true,
      message: "Reg Category 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 reg category created.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}


async function update(id, params) {
  try {
    // Validasi input
    if (!params.display_name || !params.company_id) {
      return {
        success: false,
        message: "Reg Category name and Company are required!",
      };
    }

    // Temukan kategori regulasi berdasarkan id
    const regCategory = await dbSAPPS.RegCategories.findByPk(id);
    if (!regCategory) {
      return {
        success: false,
        message: "Reg Category not found!",
      };
    }

    // Periksa apakah nama atau kode baru sudah digunakan
    const existingNameNNumber = await dbSAPPS.RegCategories.findOne({
      where: {
        display_name: params.display_name,
        company_id: params.company_id,
        id: { [Op.ne]: id },
      },
    });
    if (existingNameNNumber) {
      return {
        success: false,
        message: `Name "${params.display_name}" and company "${params.company_id}" is already taken.`,
      };
    }

    // Update data kategori regulasi
    await regCategory.update(params);

    // Respons sukses
    return {
      success: true,
      message: "Reg Category has been successfully updated!",
      regCategory,
    };
  } catch (error) {
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    const errorMessage = error.message || "An error occurred during reg category update.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}


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

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

async function _delete(id) {
  try {
    // Mengambil pengguna dari database
    const regCategory = await dbSAPPS.RegCategories.findByPk(id);
    if (!regCategory) return { success: false, message: "reg category not found!" };

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

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