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

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

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

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

/**
 * Get all workActivities with their respective companies.
 */
async function getAll(params) {
  try {
    // filter
    const filterConditions = {};

    let workActivities = [];
    workActivities = await dbSAPPS.WorkActivity.findAll({
      where: filterConditions,
      order: [["modified", "DESC"]],
      include: [
        {
          model: dbSAPPS.Employee,
          as: "employee",
          attributes: ["id", "employee_name"],
        },
        {
          model: dbSAPPS.WorkActivityItem,
          as: "workactivityitems",
        },
      ],
    });

    workActivities = workActivities.map((wa) => {
      return {
        ...wa.dataValues,
        employee_name: wa?.employee?.employee_name || null,
        total_items: wa?.workactivityitems?.length || 0,
      };
    });

    workActivities = await formatWithModifier(workActivities);

    return {
      workActivities,
      success: true,
      message: "Loaded successfully!",
    };
  } catch (error) {
    const errorMessage = error?.message || "Failed to load, please try again!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

/**
 * Get workActivities with their respective settings.
 */
async function option(params) {
  try {
    // filter
    const filterConditions = {};

    // must be enabled
    filterConditions.enabled = {
      [Op.eq]: true,
    };

    let options = [];
    options = await dbSAPPS.WorkActivity.findAll({
      where: filterConditions,
      attributes: ["id", "activity_date", "worktype", "employee_id"],
      include: [
        {
          model: dbSAPPS.Employee,
          as: "employee",
          attributes: ["id", "employee_name"],
        },
        {
          model: dbSAPPS.WorkActivityItem,
          as: "workactivityitems",
        },
      ],
      order: [["activity_date", "ASC"]],
    });

    options = options.map((option) => {
      return {
        ...option.dataValues,
      };
    });

    return {
      options,
      success: true,
      message: "Loaded successfully!",
    };
  } catch (error) {
    const errorMessage = error?.message || "Failed to load, please try again!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

/**
 * Count active workActivities
 */
async function count(params) {
  try {
    // filter
    const filterConditions = {};

    // must be enabled
    filterConditions.enabled = {
      [Op.eq]: true,
    };

    const count = await dbSAPPS.WorkActivity.count({
      where: filterConditions,
    });

    return {
      count,
      success: true,
      message: "Loaded successfully!",
    };
  } catch (error) {
    const errorMessage = error?.message || "Failed to load, please try again!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

/**
 * Creates a new workActivity
 *
 */
async function create(params) {
  const transaction = await dbSAPPS.sequelize.transaction();
  try {
    const existingWorkActivity = await dbSAPPS.WorkActivity.findOne({
      where: {
        activity_date: params.activity_date,
        employee_id: params.employee_id,
      },
      transaction,
    });

    if (existingWorkActivity) {
      return {
        success: false,
        message: `"Activity at ${params.activity_date}" is already created.`,
      };
    }

    // save
    const workActivity = await dbSAPPS.WorkActivity.create(params, { transaction });

    if (params.workactivityitems && Array.isArray(params.workactivityitems)) {
      const items = params.workactivityitems.map((item) => ({
        ...item,
        workactivity_id: workActivity.id,
        creation: new Date(),
        modified: new Date(),
        modified_by: params.modified_by,
        owner: params.owner,
        enabled: item.enabled ?? true,
      }));

      await dbSAPPS.WorkActivityItem.bulkCreate(items, { transaction });
    }

    await transaction.commit();
    return {
      success: true,
      message: "Saved successfully!",
    };
  } catch (error) {
    await transaction.rollback();
    const errorMessage = error?.message || "Failed to save, please try again!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

/**
 * Updates an existing workActivity
 *
 */
async function update(id, params) {
  const transaction = await dbSAPPS.sequelize.transaction();
  try {
    // Cek apakah work activity dengan ID tersebut ada
    const existingWorkActivity = await dbSAPPS.WorkActivity.findOne({
      where: { id },
      transaction,
    });

    if (!existingWorkActivity) {
      return {
        success: false,
        message: "Work activity not found.",
      };
    }

    // Cek duplikasi activity_date dan employee_id (kecuali untuk record yang sama)
    if (params.activity_date && params.employee_id) {
      const duplicateWorkActivity = await dbSAPPS.WorkActivity.findOne({
        where: {
          activity_date: params.activity_date,
          employee_id: params.employee_id,
          id: { [dbSAPPS.Sequelize.Op.ne]: id }, // Exclude current record
        },
        transaction,
      });

      if (duplicateWorkActivity) {
        return {
          success: false,
          message: `"Activity at ${params.activity_date}" is already created.`,
        };
      }
    }

    // Update work activity
    await dbSAPPS.WorkActivity.update(
      {
        ...params,
        modified: new Date(),
      },
      {
        where: { id },
        transaction,
      }
    );

    // Handle work activity items
    if (params.workactivityitems && Array.isArray(params.workactivityitems)) {
      // Hapus existing items
      await dbSAPPS.WorkActivityItem.destroy({
        where: { workactivity_id: id },
        transaction,
      });

      // Buat items baru
      const items = params.workactivityitems.map((item) => ({
        ...item,
        workactivity_id: id,
        creation: new Date(),
        modified: new Date(),
        modified_by: params.modified_by,
        owner: params.owner,
        enabled: item.enabled ?? true,
      }));

      await dbSAPPS.WorkActivityItem.bulkCreate(items, { transaction });
    }

    await transaction.commit();
    return {
      success: true,
      message: "Updated successfully!",
    };
  } catch (error) {
    await transaction.rollback();
    const errorMessage = error?.message || "Failed to update, please try again!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

/**
 * Enable or disable a workActivity
 * @param {number} id - the id of the workActivity
 * @param {object} params - the update data
 * @param {boolean} params.enabled - the enabled status of the workActivity
 * @param {number} [params.modified_by] - the modified by of the workActivity
 * @param {Date} [params.modified] - the modified of the workActivity
 * @returns {Promise<object>} - the result of the update
 */
async function enabled(id, params) {
  const transaction = await dbSAPPS.sequelize.transaction();
  try {
    // validate existing
    const workActivity = await dbSAPPS.WorkActivity.findByPk(id);
    if (!workActivity) return { success: false, message: "ID not found!" };

    // update params
    const updateData = {};
    updateData.enabled = params.enabled;
    if (params.modified_by) updateData.modified_by = params.modified_by;
    if (params.modified) updateData.modified = params.modified;

    // save
    await workActivity.update(updateData, { transaction });

    await transaction.commit();
    return {
      success: true,
      message: "Saved successfully!",
    };
  } catch (error) {
    await transaction.rollback();
    const errorMessage = error?.message || "Failed to save, please try again!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}

/**
 * Delete a workActivity
 * @param {number} id - the id of the workActivity
 * @returns {Promise<object>} - the result of the delete
 */
async function _delete(id) {
  const transaction = await dbSAPPS.sequelize.transaction();
  try {
    // validate existing
    const workActivity = await dbSAPPS.WorkActivity.findByPk(id, { transaction });
    if (!workActivity) return { success: false, message: "ID not found!" };

    // delete
    await workActivity.destroy({ transaction });

    await transaction.commit();
    return {
      success: true,
      message: "Deleted successfully!",
    };
  } catch (error) {
    await transaction.rollback();
    const errorMessage = error?.message || "Failed to delete, please try again!";
    return {
      success: false,
      message: errorMessage,
    };
  }
}
