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

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

    documentGroups = await formatWithModifier(documentGroups);

    // Mengembalikan respons dengan status 200 OK
    return {
      documentGroups,
      success: true,
      message: "documentGroups loaded successfully!",
    };
  } catch (error) {
    // Menangani error dan mengembalikan respons dengan status 500 Internal Server Error
    const errorMessage = error.message || "Failed to load documentGroups!";
    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 documentGroups = await dbSAPPS.DocumentGroup.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,
      documentGroups,
      message: "Document Group loaded successfully!",
    };
  } catch (error) {
    // Logging error untuk keperluan debugging
    console.error("Error retrieving Document Group: ", error);
    const errorMessage =
      error.message || "Failed to retrieve Document Group. 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 documentGroups = await dbSAPPS.DocumentGroup.findAll({
      attributes: ["id", "display_name"],
      where: { enabled: true },
      order: [["display_name", "ASC"]], // Opsional: Mengurutkan hasil berdasarkan
    });

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

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

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

    const existingNameNNumber = await dbSAPPS.DocumentGroup.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 
    await dbSAPPS.DocumentGroup.create(params);

    // Respons sukses
    return {
      success: true,
      message: "Document Group 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 document group 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: "Document Group name and Company are required!",
      };
    }

    // Temukan  berdasarkan id
    const documentGroup = await dbSAPPS.DocumentGroup.findByPk(id);
    if (!documentGroup) {
      return {
        success: false,
        message: "Document Group not found!",
      };
    }

    // Periksa apakah nama atau kode baru sudah digunakan
    const existingNameNNumber = await dbSAPPS.DocumentGroup.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
    await documentGroup.update(params);

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


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

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

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

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

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