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

/* =====================================================
   CREATE DISCOUNT (ADMIN)
   ===================================================== */
const createDiscount = async (req, res) => {
  try {
    const userId = req.user?._id;
    const orgId = req.user?.orgId;

    if (!userId || !orgId) {
      return errorResponse(res, "Unauthorized", 401);
    }

    const {
      name,
      code,
      type,
      value,
      maxDiscountAmount,
      minOrderAmount,
      appliesTo,
      isStackable,
      validFrom,
      validTill,
      isDefault,
    } = req.body;

    if (!name || !type || value === undefined) {
      return errorResponse(res, "Required fields missing", 400);
    }

    // Prevent duplicate discount name per org
    const exists = await Discount.findOne({
      name,
      orgId,
      isDeleted: false,
    });

    if (exists) {
      return errorResponse(res, "Discount with this name already exists", 409);
    }

    // Only one default discount per org
    if (isDefault === true) {
      await Discount.updateMany(
        { orgId, isDefault: true },
        { isDefault: false }
      );
    }

    const discount = await Discount.create({
      name,
      code,
      type,
      value,
      maxDiscountAmount,
      minOrderAmount,
      appliesTo,
      isStackable,
      validFrom,
      validTill,
      isDefault: !!isDefault,
      isActive: true,
      orgId,
      createdBy: userId,
    });

    await logUserAction({
      userId,
      orgId,
      action: "CREATE_DISCOUNT",
      model: "Discount",
      details: {
        discountId: discount._id,
        name: discount.name,
        type: discount.type,
        value: discount.value,
      },
      req,
    });

    return res.status(201).json({
      success: true,
      data: discount,
    });
  } catch (err) {
    console.error("CREATE DISCOUNT ERROR:", err);
    return errorResponse(
      res,
      err.message || "Failed to create discount",
      500,
      err
    );
  }
};

/* =====================================================
   GET ALL DISCOUNTS (ADMIN / MANAGER)
   ===================================================== */
const getAllDiscounts = async (req, res) => {
  try {
    const orgId = req.user?.orgId;

    const discounts = await Discount.find({
      orgId,
      isDeleted: false,
    }).sort({ createdAt: -1 });

    return res.json({
      success: true,
      data: discounts,
    });
  } catch (err) {
    return errorResponse(res, "Failed to fetch discounts", 500, err);
  }
};

/* =====================================================
   GET ACTIVE DEFAULT DISCOUNT
   (Used by Invoice Service)
   ===================================================== */
const getActiveDefaultDiscount = async (req, res) => {
  try {
    const orgId = req.user?.orgId;

    const discount = await Discount.findOne({
      orgId,
      isActive: true,
      isDefault: true,
      isDeleted: false,
    });

    if (!discount) {
      return errorResponse(res, "No active default discount found", 404);
    }

    return res.json({
      success: true,
      data: discount,
    });
  } catch (err) {
    return errorResponse(res, "Failed to fetch default discount", 500, err);
  }
};

/* =====================================================
   UPDATE DISCOUNT
   ===================================================== */
const updateDiscount = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user?._id;
    const orgId = req.user?.orgId;

    const discount = await Discount.findOne({
      _id: id,
      orgId,
      isDeleted: false,
    });

    if (!discount) {
      return errorResponse(res, "Discount not found", 404);
    }

    // Handle default switch
    if (req.body.isDefault === true) {
      await Discount.updateMany(
        { orgId, isDefault: true },
        { isDefault: false }
      );
    }

    Object.assign(discount, req.body);
    discount.updatedBy = userId;

    await discount.save();

    await logUserAction({
      userId,
      orgId,
      action: "UPDATE_DISCOUNT",
      model: "Discount",
      details: {
        discountId: discount._id,
        updatedFields: Object.keys(req.body),
      },
      req,
    });

    return res.json({
      success: true,
      data: discount,
    });
  } catch (err) {
    console.error("UPDATE DISCOUNT ERROR:", err);
    return errorResponse(
      res,
      err.message || "Failed to update discount",
      500,
      err
    );
  }
};

/* =====================================================
   ACTIVATE / DEACTIVATE DISCOUNT
   ===================================================== */
const toggleDiscountStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user?._id;
    const orgId = req.user?.orgId;

    const discount = await Discount.findOne({
      _id: id,
      orgId,
      isDeleted: false,
    });

    if (!discount) {
      return errorResponse(res, "Discount not found", 404);
    }

    discount.isActive = !discount.isActive;
    discount.updatedBy = userId;
    await discount.save();

    await logUserAction({
      userId,
      orgId,
      action: discount.isActive
        ? "ACTIVATE_DISCOUNT"
        : "DEACTIVATE_DISCOUNT",
      model: "Discount",
      details: {
        discountId: discount._id,
        isActive: discount.isActive,
      },
      req,
    });

    return res.json({
      success: true,
      data: discount,
    });
  } catch (err) {
    return errorResponse(
      res,
      "Failed to update discount status",
      500,
      err
    );
  }
};

/* =====================================================
   DELETE DISCOUNT (SOFT DELETE)
   ===================================================== */
const deleteDiscount = async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user?._id;
    const orgId = req.user?.orgId;

    const discount = await Discount.findOne({
      _id: id,
      orgId,
      isDeleted: false,
    });

    if (!discount) {
      return errorResponse(res, "Discount not found", 404);
    }

    discount.isDeleted = true;
    discount.isActive = false;
    discount.updatedBy = userId;

    await discount.save();

    await logUserAction({
      userId,
      orgId,
      action: "DELETE_DISCOUNT",
      model: "Discount",
      details: {
        discountId: discount._id,
        name: discount.name,
      },
      req,
    });

    return res.json({
      success: true,
      message: "Discount deleted successfully",
    });
  } catch (err) {
    return errorResponse(res, "Failed to delete discount", 500, err);
  }
};

/* =====================================================
   EXPORTS
   ===================================================== */
module.exports = {
  createDiscount,
  getAllDiscounts,
  getActiveDefaultDiscount,
  updateDiscount,
  toggleDiscountStatus,
  deleteDiscount,
};
