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

/* =====================================================
   CREATE TAX (ADMIN)
   ===================================================== */
const createTax = async (req, res) => {
  try {
    const { name, type, rates, applicableFor, isDefault } = req.body;
    const userId = req.user?._id;
    const orgId = req.user?.orgId;

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

    if (!name) {
      return errorResponse(res, "Tax name is required", 400);
    }

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

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

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

    const tax = await Tax.create({
      name,
      type,
      rates,
      applicableFor,
      isDefault: !!isDefault,
      isActive: true,
      orgId,
      createdBy: userId,
    });

    await logUserAction({
      userId,
      orgId,
      action: "CREATE_TAX",
      model: "Tax",
      details: {
        taxId: tax._id,
        name: tax.name,
        totalRate: tax.totalRate,
      },
      req,
    });

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

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

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

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

/* =====================================================
   GET ACTIVE DEFAULT TAX (USED BY INVOICE SERVICE)
   ===================================================== */
const getActiveDefaultTax = async (req, res) => {
  try {
    const orgId = req.user?.orgId;

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

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

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

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

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

    if (!tax) {
      return errorResponse(res, "Tax not found", 404);
    }

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

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

    await tax.save();

    await logUserAction({
      userId,
      orgId,
      action: "UPDATE_TAX",
      model: "Tax",
      details: {
        taxId: tax._id,
        updatedFields: Object.keys(req.body),
      },
      req,
    });

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

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

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

    if (!tax) {
      return errorResponse(res, "Tax not found", 404);
    }

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

    await logUserAction({
      userId,
      orgId,
      action: tax.isActive ? "ACTIVATE_TAX" : "DEACTIVATE_TAX",
      model: "Tax",
      details: {
        taxId: tax._id,
        isActive: tax.isActive,
      },
      req,
    });

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

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

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

    if (!tax) {
      return errorResponse(res, "Tax not found", 404);
    }

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

    await tax.save();

    await logUserAction({
      userId,
      orgId,
      action: "DELETE_TAX",
      model: "Tax",
      details: {
        taxId: tax._id,
        name: tax.name,
      },
      req,
    });

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

/* =====================================================
   EXPORTS
   ===================================================== */
module.exports = {
  createTax,
  getAllTaxes,
  getActiveDefaultTax,
  updateTax,
  toggleTaxStatus,
  deleteTax,
};
