const SellerAuditTrail = require("../models/SellerAuditTrail");
const { Op } = require("sequelize");

exports.createAuditTrail = async ({
  seller_id,
  seller_company_id,
  module,
  action,
  action_description = "",
}) => {
  try {
    let success = false;

    const createdTrail = await SellerAuditTrail.create({
      seller_id,
      seller_company_id,
      module,
      action,
      action_description,
    });

    if (createdTrail) {
      success = true;
    }

    return success;
  } catch (err) {
    return false;
  }
};

exports.getSellerAuditTrailPaginate = async ({
  page = 1,
  limit = 10,
  seller_id,
  keyword = "",
}) => {
  try {
    const offset = (page - 1) * limit;

    const whereCondition = {
      seller_company_id: seller_id,
    };

    if (keyword && keyword.trim() !== "") {
      const likeKeyword = `%${keyword.trim()}%`;
      whereCondition[Op.or] = [
        { module: { [Op.like]: likeKeyword } },
        { action: { [Op.like]: likeKeyword } },
        { action_description: { [Op.like]: likeKeyword } },
      ];
    }

    const { rows, count } = await SellerAuditTrail.findAndCountAll({
      where: whereCondition,
      order: [["createdAt", "DESC"]],
      limit,
      offset,
    });

    return {
      data: rows,
      total: count,
      currentPage: page,
      totalPages: Math.ceil(count / limit),
    };
  } catch (err) {
    console.error("Error fetching audit trail:", err);
    return {
      data: [],
      total: 0,
      currentPage: page,
      totalPages: 0,
      error: true,
      message: "Failed to retrieve audit trail.",
    };
  }
};
