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

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

    dmsRegulatories = await formatWithModifier(dmsRegulatories);

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

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

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

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

    const existingNameNNumber = await dbSAPPS.DMSRegulatory.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.`,
      };
    }

    if (!params.enabled) {
      params.enabled = true;
    }

    if (params?.user_info) {
      params.user_info = JSON.parse(params.user_info);
    }

    // Create data
    await dbSAPPS.DMSRegulatory.create(params);

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

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

    // Periksa apakah nama atau kode baru sudah digunakan
    const existingNameNNumber = await dbSAPPS.DMSRegulatory.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.`,
      };
    }

    if (params?.user_info) {
      params.user_info = JSON.parse(params.user_info);
    }

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

    // Respons sukses
    return {
      success: true,
      message: "Document 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 update.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function enabled(id, params) {
  try {
    const documentGroup = await dbSAPPS.DMSRegulatory.findByPk(id);
    if (!documentGroup)
      return {
        success: false,
        message: "Document 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 has been updated!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to update Document.";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

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

    // menghapus document dari path
    if (
      dmsRA.document_1 ||
      dmsRA.document_2 ||
      dmsRA.document_3 ||
      dmsRA.history_doc ||
      dmsRA.history_doc2 ||
      dmsRA.history_doc3 ||
      dmsRA.history_doc4 ||
      dmsRA.history_doc5
    ) {
      const fs = require("fs").promises;
      const path = require("path");
      if (dmsRA.document_1) {
        const filePath = path.resolve(
          __dirname,
          "../../../../public/data/documents/",
          dmsRA.document_1?.split("/documents/")[1]
        );
        await fs.unlink(filePath);
      }
      if (dmsRA.document_2) {
        const filePath = path.resolve(
          __dirname,
          "../../../../public/data/documents/",
          dmsRA.document_2?.split("/documents/")[1]
        );
        await fs.unlink(filePath);
      }
      if (dmsRA.document_3) {
        const filePath = path.resolve(
          __dirname,
          "../../../../public/data/documents/",
          dmsRA.document_3?.split("/documents/")[1]
        );
        await fs.unlink(filePath);
      }
      if (dmsRA.history_doc) {
        const filePath = path.resolve(
          __dirname,
          "../../../../public/data/documents/",
          dmsRA.history_doc?.split("/documents/")[1]
        );
        await fs.unlink(filePath);
      }
      if (dmsRA.history_doc2) {
        const filePath = path.resolve(
          __dirname,
          "../../../../public/data/documents/",
          dmsRA.history_doc2?.split("/documents/")[1]
        );
        await fs.unlink(filePath);
      }
      if (dmsRA.history_doc3) {
        const filePath = path.resolve(
          __dirname,
          "../../../../public/data/documents/",
          dmsRA.history_doc3?.split("/documents/")[1]
        );
        await fs.unlink(filePath);
      }
      if (dmsRA.history_doc4) {
        const filePath = path.resolve(
          __dirname,
          "../../../../public/data/documents/",
          dmsRA.history_doc4?.split("/documents/")[1]
        );
        await fs.unlink(filePath);
      }
      if (dmsRA.history_doc5) {
        const filePath = path.resolve(
          __dirname,
          "../../../../public/data/documents/",
          dmsRA.history_doc5?.split("/documents/")[1]
        );
        await fs.unlink(filePath);
      }
    }

    await dmsRA.destroy();

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