// controllers/admin/adminUserTradingController.js
const ApiResponse = require("../../utils/apiResponse");
const { asyncHandler } = require("../../middleware/errorHandler");
const adminUserTradingService = require("../../services/admin/tradingService");
const { BadRequestError } = require("../../utils/errors");
const placeTradeService = require("../../services/admin/placeTradeService");

// ------------------------------
// PORTFOLIO
// ------------------------------
exports.listHoldings = asyncHandler(async (req, res) => {
  const data = await adminUserTradingService.listHoldings(req.query);
  ApiResponse.success(res, data);
});

exports.listHoldingsByUser = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const data = await adminUserTradingService.listUserHoldings(userId, req.query);
  ApiResponse.success(res, data);
});

exports.listLots = asyncHandler(async (req, res) => {
  const data = await adminUserTradingService.listLots(req.query);
  ApiResponse.success(res, data);
});

exports.listLotsByUser = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const data = await adminUserTradingService.listUserLots(userId, req.query);
  ApiResponse.success(res, data);
});

exports.addDividends = asyncHandler(async (req, res) => {
  const data = await adminUserTradingService.addDividends( req.body.assetId, req.body.amount, req.body.type, req.admin?.id);
  ApiResponse.success(res, data);
});

exports.adjustHolding = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const holding = await adminUserTradingService.adjustHolding(userId, req.body, req.admin?.id);
  ApiResponse.success(res, { holding }, "Holding adjusted");
});

exports.addLots = asyncHandler(async (req, res) => {
  const data = await adminUserTradingService.addLots(req.body);
  ApiResponse.success(res, data);
});

exports.deleteHolding = asyncHandler(async (req, res) => {
  const {id} = req?.params;
  if(!id) throw new BadRequestError("Invalid Id")
  const data = await adminUserTradingService.deleteHolding(id);
  ApiResponse.success(res, data);
});

// ------------------------------
// SPOT
// ------------------------------
exports.listSpotOrders = asyncHandler(async (req, res) => {
 
  const data = await adminUserTradingService.listSpotOrders(req.query);
  ApiResponse.success(res, data);
});

exports.listSpotOrdersByUser = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const data = await adminUserTradingService.listUserSpotOrders(userId, req.query);
  ApiResponse.success(res, data);
});

exports.cancelSpotOrder = asyncHandler(async (req, res) => {
  const { userId, orderId } = req.params;
  const order = await adminUserTradingService.cancelSpotOrder(userId, orderId, req.admin?.id);
  ApiResponse.success(res, { order }, "Spot order canceled");
});

exports.listSpotTrades = asyncHandler(async (req, res) => {
  const data = await adminUserTradingService.listSpotTrades(req.query);
  ApiResponse.success(res, data);
});

exports.listSpotTradesByUser = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const data = await adminUserTradingService.listUserSpotTrades(userId, req.query);
  ApiResponse.success(res, data);
});

// ------------------------------
// DERIVATIVES
// ------------------------------
exports.listDerivativeAccounts = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const data = await adminUserTradingService.listDerivativeAccounts(userId, req.query);
  ApiResponse.success(res, data);
});

exports.listDerivativeAccountsByUser = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const data = await adminUserTradingService.listUserDerivativeAccounts(userId, req.query);
  ApiResponse.success(res, data);
});

exports.restrictDerivativeAccount = asyncHandler(async (req, res) => {
  const { userId, accountId } = req.params;
  const account = await adminUserTradingService.setDerivativeAccountStatus(
    userId,
    accountId,
    "restricted",
    req.admin?.id
  );
  ApiResponse.success(res, { account }, "Derivative account restricted");
});

exports.activateDerivativeAccount = asyncHandler(async (req, res) => {
  const { userId, accountId } = req.params;
  const account = await adminUserTradingService.setDerivativeAccountStatus(
    userId,
    accountId,
    "active",
    req.admin?.id
  );
  ApiResponse.success(res, { account }, "Derivative account activated");
});

exports.listDerivativeOrders = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const data = await adminUserTradingService.listDerivativeOrders(userId, req.query);
  ApiResponse.success(res, data);
});

exports.listDerivativeOrdersByUser = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const data = await adminUserTradingService.listUserDerivativeOrders(userId, req.query);
  ApiResponse.success(res, data);
});

exports.cancelDerivativeOrder = asyncHandler(async (req, res) => {
  const { userId, orderId } = req.params;
  const order = await adminUserTradingService.cancelDerivativeOrder(userId, orderId, req.admin?.id);
  ApiResponse.success(res, { order }, "Derivative order canceled");
});

exports.listDerivativePositions = asyncHandler(async (req, res) => {
 console.log("Query: ", req.query);
  const data = await adminUserTradingService.listDerivativePositions(req.query);
  ApiResponse.success(res, data);
});

exports.deleteDerivativePositions = asyncHandler(async (req, res) => {
  const {id} = req?.params;
  if(!id) throw new BadRequestError("Invalid Id")
  const data = await adminUserTradingService.deleteDerivativePositions(id);
  ApiResponse.success(res, data);
});

exports.listDerivativePositionsByUser = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  console.log("Query: ", req.query);
  const data = await adminUserTradingService.listUserDerivativePositions(userId, req.query);
  ApiResponse.success(res, data);
});



exports.listDerivativeTrades = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const data = await adminUserTradingService.listDerivativeTrades(userId, req.query);
  ApiResponse.success(res, data);
});

exports.listDerivativeTradesByUser = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const data = await adminUserTradingService.listUserDerivativeTrades(userId, req.query);
  ApiResponse.success(res, data);
});

exports.listPairs = asyncHandler(async (req, res) => {
  const data = await adminUserTradingService.listPairs();
  ApiResponse.success(res, data);
});

//Option Tradings
exports.listUserOptions = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const data = await adminUserTradingService.listUserOptions(userId, req.query);
  ApiResponse.success(res, data);
});

exports.listOptions = asyncHandler(async (req, res) => {
 
  const data = await adminUserTradingService.listOptions(req.query);
  ApiResponse.success(res, data);
});

exports.deleteOptionHistory = asyncHandler(async (req, res) => {
  const {id} = req?.params;
  if(!id) throw new BadRequestError("Invalid Id")
  const data = await adminUserTradingService.deleteOptionHistory(id);
  ApiResponse.success(res, data);
});

//Terminal Tradings
exports.listTrades = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const data = await adminUserTradingService.listTrades(userId, req.query);
  ApiResponse.success(res, data);
});



exports.listTradesByUser = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const data = await adminUserTradingService.listUserTrades(userId, req.query);
  ApiResponse.success(res, data);
});

exports.deleteTradeHistory = asyncHandler(async (req, res) => {
  const {id} = req?.params;
  if(!id) throw new BadRequestError("Invalid Id")
  const data = await adminUserTradingService.deleteTradeHistory(id);
  ApiResponse.success(res, data);
});

exports.tradeStock = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const data = await adminUserTradingService.tradeStock(userId , req.body);
  ApiResponse.success(res, data);
});


exports.tradeTerminal = asyncHandler(async (req, res) => {
  const { userId } = req.params;
  const data = await adminUserTradingService.tradeTerminal(userId , req.body);
  ApiResponse.success(res, data);
});

// controllers/adminUserTradingController.js

exports.editHolding = asyncHandler(async (req, res) => {
  const { holdingId } = req.params;
  const { update_balance, ...fields } = req.body;
  const data = await adminUserTradingService.editHolding(
    Number(holdingId),
    fields,
    update_balance === true || update_balance === "true"
  );
  ApiResponse.success(res, data);
});

exports.editDerivativePosition = asyncHandler(async (req, res) => {
  const { positionId } = req.params;
  const { update_balance, ...fields } = req.body;
  const data = await adminUserTradingService.editDerivativePosition(
    Number(positionId),
    fields,
    update_balance === true || update_balance === "true"
  );
  ApiResponse.success(res, data);
});

exports.editSpotOrder = asyncHandler(async (req, res) => {
  const { orderId } = req.params;
  const { update_balance, ...fields } = req.body;
  const data = await adminUserTradingService.editSpotOrder(
    Number(orderId),
    fields,
    update_balance === true || update_balance === "true"
  );
  ApiResponse.success(res, data);
});

exports.editTerminalTrade = asyncHandler(async (req, res) => {
  const { tradeId } = req.params;
  const { update_balance, ...fields } = req.body;
  const data = await adminUserTradingService.editTerminalTrade(
    Number(tradeId),
    fields,
    update_balance === true || update_balance === "true"
  );
  ApiResponse.success(res, data);
});

exports.editBinaryOption = asyncHandler(async (req, res) => {
  const { tradeId } = req.params;
  const { update_balance, ...fields } = req.body;
  const data = await adminUserTradingService.editBinaryOption(
    Number(tradeId),
    fields,
    update_balance === true || update_balance === "true"
  );
  ApiResponse.success(res, data);
});

// controllers/adminUserTradingController.js  (close section)

/**
 * Body shape (from frontend):
 * {
 *   closeType: "auto" | "manual",
 *   price:       number   (manual only — used as exit/result price)
 *   profit:      number   (manual only — override realized profit)
 *   entry_price: number   (manual only — override entry price before PnL)
 * }
 */

exports.closeDerivativePosition = asyncHandler(async (req, res) => {
  const { positionId } = req.params;
  const { closeType = "auto", price, profit, entry_price } = req.body;
  const data = await adminUserTradingService.adminCloseDerivativePosition(
    Number(positionId),
    { closeType, price: Number(price || 0), profit: Number(profit || 0), entry_price: Number(entry_price || 0) }
  );
  ApiResponse.success(res, data);
});

exports.closeTerminalTrade = asyncHandler(async (req, res) => {
  const { tradeId } = req.params;
  const { closeType = "auto", price, profit, entry_price } = req.body;
  const data = await adminUserTradingService.adminCloseTerminalTrade(
    Number(tradeId),
    { closeType, price: Number(price || 0), profit: Number(profit || 0), entry_price: Number(entry_price || 0) }
  );
  ApiResponse.success(res, data);
});

exports.settleBinaryOption = asyncHandler(async (req, res) => {
  const { tradeId } = req.params;
  const { closeType = "auto", price, profit } = req.body;
  const data = await adminUserTradingService.adminSettleBinaryOption(
    Number(tradeId),
    { closeType, price: Number(price || 0), profit: Number(profit || 0) }
  );
  ApiResponse.success(res, data);
});

exports.allTradingData = asyncHandler(async (req, res) => {
  const data = await adminUserTradingService.allTradingData();
  ApiResponse.success(res, data);
});

exports.tradeAsset = asyncHandler(async (req, res) => {
  const data = await placeTradeService.tradeAsset(req?.body);
  ApiResponse.success(res, data);
});

exports.tradeTerminal = asyncHandler(async (req, res) => {
  const data = await placeTradeService.tradeTerminal(req?.body);
  ApiResponse.success(res, data);
});

exports.tradeForex = asyncHandler(async (req, res) => {
  const data = await placeTradeService.tradeForex(req?.body);
  ApiResponse.success(res, data);
});

exports.tradeSpot = asyncHandler(async (req, res) => {
  const data = await placeTradeService.tradeSpot(req?.body);
  ApiResponse.success(res, data);
});

exports.tradeOption = asyncHandler(async (req, res) => {
  const data = await placeTradeService.tradeOption(req?.body);
  ApiResponse.success(res, data);
});