const Variant = require("../../models/admin/variantModel");
const { errorResponse } = require("../../utils/errorResponseHandler");
const { logUserAction } = require("../../utils/userActionLogger");


// CREATE Variant
const createVariant = async (req, res) => {
  try {
    const { variantName, values, orgId } = req.body;
    const userId = req.user?._id;

    if (!variantName) return errorResponse(res, "Variant name is required", 400);
    if (!Array.isArray(values) || values.length === 0)
      return errorResponse(res, "Variant values are required", 400);
    if (!orgId) return errorResponse(res, "Organization ID is required", 400);

    // Check if variant with same name exists in the org
    const existingVariant = await Variant.findOne({ variantName, orgId });
    if (existingVariant) {
      return errorResponse(
        res,
        "Variant name already exists in this organization",
        409
      ); // 409 = Conflict
    }

    const variant = await Variant.create({
      variantName,
      values,
      orgId,
      createdBy: userId || null,
      updatedBy: userId || null,
    });

    // Log user action
    await logUserAction({
      userId,
      orgId,
      action: "CREATE",
      model: "Variant",
      details: { variantId: variant._id, variantName },
      req,
    });

    res.status(201).json({ success: true, data: variant });
  } catch (error) {
    return errorResponse(res, "Failed to create variant", 400, error);
  }
};

// GET All Variants with Pagination
const getVariants = async (req, res) => {
  try {
    let { page = 1, limit = 10 } = req.query;
    page = parseInt(page);
    limit = parseInt(limit);
    const skip = (page - 1) * limit;

    const query = { isDeleted: false };

    const [variants, total] = await Promise.all([
      Variant.find(query)
        .populate("createdBy", "firstName lastName email")
        .populate("updatedBy", "firstName lastName email")
        .populate("orgId", "orgName")
        .skip(skip)
        .limit(limit)
        .sort({ createdAt: -1 }),
      Variant.countDocuments(query),
    ]);

    // Log user action
    await logUserAction({
      userId: req.user?._id,
      // userId : req.user.id,
      orgId: null,
      action: "READ",
      model: "Variant",
      details: { page, limit, count: variants.length },
      req,
    });

    res.status(200).json({
      success: true,
      page,
      totalPages: Math.ceil(total / limit),
      totalRecords: total,
      data: variants,
    });
  } catch (error) {
    return errorResponse(res, "Failed to fetch variants", 500, error);
  }
};

// GET Variant by ID
const getVariantById = async (req, res) => {
  try {
    const variant = await Variant.findById(req.params.id)
      .populate("createdBy", "firstName lastName email")
      .populate("updatedBy", "firstName lastName email")
      .populate("orgId", "orgName");

    if (!variant) return errorResponse(res, "Variant not found", 404);

    // Log user action
    await logUserAction({
      // userId: req.user?._id,
      userId: req.user.id,
      orgId: variant.orgId,
      action: "READ",
      model: "Variant",
      details: { variantId: variant._id },
      req,
    });

    res.status(200).json({ success: true, data: variant });
  } catch (error) {
    return errorResponse(res, "Failed to fetch variant", 500, error);
  }
};

// UPDATE Variant
// const updateVariant = async (req, res) => {
//   try {
//     const { variantName, values, status, orgId } = req.body;
//     const userId = req.user?._id;

//     const updateData = { updatedBy: userId || null };
//     if (variantName) updateData.variantName = variantName;
//     if (Array.isArray(values) && values.length > 0) updateData.values = values;
//     if (status !== undefined) updateData.status = status;
//     if (orgId) updateData.orgId = orgId;

//     const variant = await Variant.findByIdAndUpdate(
//       req.params.id,
//       updateData,
//       { new: true, runValidators: true }
//     )
//       .populate("createdBy", "firstName lastName email")
//       .populate("updatedBy", "firstName lastName email")
//       .populate("orgId", "orgName");

//     if (!variant) return errorResponse(res, "Variant not found", 404);

//     // Log user action
//     await logUserAction({
//       userId,
//       orgId: variant.orgId,
//       action: "UPDATE",
//       model: "Variant",
//       details: { variantId: variant._id, updatedFields: updateData },
//       req,
//     });

//     res.status(200).json({ success: true, data: variant });
//   } catch (error) {
//     return errorResponse(res, "Failed to update variant", 400, error);
//   }
// };
const updateVariant = async (req, res) => {
  try {
    const { variantName, values, status, orgId } = req.body;
    const userId = req.user?._id;

    //  DUPLICATE VARIANT CHECK (exclude current variant)
    if (variantName) {
      const duplicate = await Variant.findOne({
        _id: { $ne: req.params.id }, // exclude current variant
        variantName: {
          $regex: `^${variantName}$`,
          $options: "i", // case-insensitive
        },
        orgId,
        isDeleted: false,
      });

      if (duplicate) {
        return errorResponse(
          res,
          "Variant already exists in this organization",
          409
        );
      }
    }

    // BUILD UPDATE DATA
    const updateData = {
      updatedBy: userId || null,
      updatedAt: new Date(), //  always update timestamp
    };

    if (variantName) updateData.variantName = variantName;
    if (Array.isArray(values)) updateData.values = values;
    if (status !== undefined) updateData.status = status;
    if (orgId) updateData.orgId = orgId;

    const variant = await Variant.findByIdAndUpdate(
      req.params.id,
      updateData,
      { new: true, runValidators: true }
    )
      .populate("createdBy", "firstName lastName email")
      .populate("updatedBy", "firstName lastName email")
      .populate("orgId", "orgName");

    if (!variant) return errorResponse(res, "Variant not found", 404);

    // LOG ACTION
    await logUserAction({
      userId,
      orgId: variant.orgId?._id || orgId || null,
      action: "UPDATE",
      model: "Variant",
      details: { variantId: variant._id, updatedFields: updateData },
      req,
    });

    return res.status(200).json({
      success: true,
      data: variant,
    });
  } catch (error) {
    return errorResponse(res, "Failed to update variant", 400, error);
  }
};


// Soft Delete Variant
const deleteVariant = async (req, res) => {
  try {
    const userId = req.user?._id;

    const variant = await Variant.findByIdAndUpdate(
      req.params.id,
      { isDeleted: true, updatedBy: userId || null },
      { new: true }
    );

    if (!variant) return errorResponse(res, "Variant not found", 404);

    // Log user action
    await logUserAction({
      userId,
      orgId: variant.orgId,
      action: "DELETE",
      model: "Variant",
      details: { variantId: variant._id },
      req,
    });

    res.status(200).json({
      success: true,
      message: "Variant deleted successfully",
      data: variant,
    });
  } catch (error) {
    return errorResponse(res, "Failed to delete variant", 500, error);
  }
};

module.exports = {
  createVariant,
  getVariants,
  getVariantById,
  updateVariant,
  deleteVariant,
};
