const { Op, Sequelize } = 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 dmsLegals = await dbSAPPS.DMSLegal.findAll({
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.DMSLegalChild,
          as: "dmslegalchilds",
          attributes: [
            "id",
            "dmslegal_id",
            "name",
            "document_number",
            "counter_part",
            "date",
            "exp_date",
            "original",
            "copy",
            "remark",
            "softfile",
            "registration_number",
            "status",
            "owner_doc",
            "class",
          ],
        },
        {
          model: dbSAPPS.Company,
          as: "company",
          attributes: ["name"],
        },
      ],
    });

    return {
      dmsLegals,
      success: true,
      message: "DMS Legals loaded successfully!",
    };
  } catch (error) {
    const errorMessage = error.message || "Failed to load DMS Legals!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

async function filter(params) {
  const filterConditions = {};

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

  try {
    const dmsLegals = await dbSAPPS.DMSLegal.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.DMSLegalChild,
          as: "dmslegalchilds",
          attributes: [
            "id",
            "dmslegal_id",
            "name",
            "document_number",
            "counter_part",
            "date",
            "exp_date",
            "original",
            "copy",
            "remark",
            "softfile",
            "registration_number",
            "status",
            "owner_doc",
            "class",
          ],
        },
        {
          model: dbSAPPS.Company,
          as: "company",
          attributes: ["name"],
        },
      ],
    });

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

async function option() {
  try {
    const dmsLegals = await dbSAPPS.DMSLegal.findAll({
      where: { enabled: true },
      order: [["type", "ASC"]],
      include: [
        {
          model: dbSAPPS.DMSLegalChild,
          as: "dmslegalchilds",
          attributes: [
            "id",
            "dmslegal_id",
            "name",
            "document_number",
            "counter_part",
            "date",
            "exp_date",
            "original",
            "copy",
            "remark",
            "softfile",
            "registration_number",
            "status",
            "owner_doc",
            "class",
          ],
        },
        {
          model: dbSAPPS.Company,
          as: "company",
          attributes: ["name"],
        },
      ],
    });

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

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

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

async function create(params) {
  const transaction = await dbSAPPS.sequelize.transaction();
  try {
    if (!params.enabled) params.enabled = true;

    const existing = await dbSAPPS.DMSLegal.findOne({
      where: {
        type: params.type,
        sub_type: params.sub_type,
        category: params.category,
        sub_category: params.sub_category,
        company_id: params.company_id,
      },
    });
    if (existing)
      return {
          success: false,
          message: `This folder has already been created.`,
      };
    // Buat DMS Legal baru
    const newDMSLegal = await dbSAPPS.DMSLegal.create(params, { transaction });

    // Proses child data jika ada
    if (params.dmslegalchilds) {
      if (typeof params.dmslegalchilds === "string") {
        params.dmslegalchilds = JSON.parse(params.dmslegalchilds);
      }

      // Tambahkan file softfile ke child data
      params.dmslegalchilds = params.dmslegalchilds.map((child, index) => ({
        ...child,
        softfile: params[`softfile_${index}`] || null, // Simpan file jika ada
        creation: Date.now(),
        modified: Date.now(),
        modified_by: params.modified_by,
        owner: params.owner,
        dmslegal_id: newDMSLegal.id,
      }));

      await dbSAPPS.DMSLegalChild.bulkCreate(params.dmslegalchilds, {
        transaction,
      });
    }

    await transaction.commit();
    return {
      success: true,
      message: "Data DMS Legal has been successfully added!",
      dmsLegals: newDMSLegal,
    };
  } catch (error) {
    await transaction.rollback();
    return {
      success: false,
      message: error.message || "An error occurred during DMS legal creation.",
    };
  }
}

async function update(id, params) {
  const transaction = await dbSAPPS.sequelize.transaction();
  try {
    const dmsLegal = await dbSAPPS.DMSLegal.findByPk(id);
    if (!dmsLegal) {
      return { success: false, message: "DMS legal not found!" };
    }

    // Update DMS Legal
    await dmsLegal.update(params, { transaction });

    // Update atau tambahkan child data
    if (params.dmslegalchilds) {
      if (typeof params.dmslegalchilds === "string") {
        params.dmslegalchilds = JSON.parse(params.dmslegalchilds);
      }

      // Ambil data child lama
      const existingChildren = await dbSAPPS.DMSLegalChild.findAll({
        where: { dmslegal_id: id },
      });

      const updatedChildren = params.dmslegalchilds.map((child, index) => {
        const existingChild = existingChildren.find((c) => c.id === child.id);
        return {
          ...child,
          softfile:
            params[`softfile_${index}`] ||
            (existingChild ? existingChild.softfile : null),
          modified: Date.now(),
          modified_by: params.modified_by,
        };
      });

      // Hapus child lama & masukkan data baru
      await dbSAPPS.DMSLegalChild.destroy({
        where: { dmslegal_id: id },
        transaction,
      });

      // Persiapkan data untuk bulkCreate
      const dmsLegalChildData = params.dmslegalchilds.map((dmsLegalChild) => {
        // Validasi field yang diperlukan
        if (!dmsLegalChild.name) {
          throw new Error("Missing required fields in delivery trip child.");
        }

        return {
          ...dmsLegalChild,
          creation: Date.now(),
          modified: Date.now(),
          modified_by: params.modified_by,
          owner: params.owner,
          dmslegal_id: id, // Mengaitkan dengan ID Delivery Trip yang diupdate
        };
      });

      await dbSAPPS.DMSLegalChild.bulkCreate(dmsLegalChildData, {
        transaction,
      });
    }

    await transaction.commit();
    return { success: true, message: "Your data DMS Legal has been updated!" };
  } catch (error) {
    await transaction.rollback();
    return {
      success: false,
      message: error.message || "Failed to update DMS legal data.",
    };
  }
}

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

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

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

    await dmsLegal.destroy();

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