// controllers/watchlistController.js
const WatchlistService = require("../services/watchlistService");
const { asyncHandler }  = require("../middleware/errorHandler");
const ApiResponse        = require("../utils/apiResponse");
const { mapWatchlist }   = require("../utils/helpers");

// ─── Watchlist ───────────────────────────────────────────────

exports.getWatchlist = asyncHandler(async (req, res) => {
  const userId = req.user?.id;
  const data   = await WatchlistService.getWatchlist(userId);
  return ApiResponse.success(res, data);
});

exports.addItem = asyncHandler(async (req, res) => {
  const userId      = req.user?.id;
  const { symbol }  = req.body;

  if (!symbol) return ApiResponse.error(res, "symbol is required", 400);

  const created = await WatchlistService.addToWatchlist({ userId, symbol });
  const data    = await WatchlistService.getWatchlist(userId);

  return ApiResponse.success(res, {
    success: true,
    asset:   mapWatchlist(created),
    ...data,
  }, "Added to watchlist");
});

exports.removeItem = asyncHandler(async (req, res) => {
  const userId      = req.user?.id;
  const { id }      = req.params;

  const ok   = await WatchlistService.removeFromWatchlist({ userId, itemId: id });
  const data = await WatchlistService.getWatchlist(userId);

  return ApiResponse.success(res, { success: ok, ...data }, "Removed from watchlist");
});

// ─── Alerts ──────────────────────────────────────────────────

exports.createAlert = asyncHandler(async (req, res) => {
  const userId = req.user?.id;
  const { watchlistId, symbol, type, targetPrice } = req.body;

  if (!watchlistId || !symbol || !type || targetPrice == null) {
    return ApiResponse.error(res, "watchlistId, symbol, type and targetPrice are required", 400);
  }
  if (!["above", "below"].includes(type)) {
    return ApiResponse.error(res, "type must be 'above' or 'below'", 400);
  }
  if (Number.isNaN(Number(targetPrice)) || Number(targetPrice) <= 0) {
    return ApiResponse.error(res, "targetPrice must be a positive number", 400);
  }

  await WatchlistService.createAlert({ userId, watchlistId, symbol, type, targetPrice });
  const data = await WatchlistService.getWatchlist(userId);

  return ApiResponse.success(res, { success: true, ...data }, "Alert created");
});

exports.toggleAlert = asyncHandler(async (req, res) => {
  const userId  = req.user?.id;
  const { id }  = req.params;

  await WatchlistService.toggleAlert({ userId, alertId: id });
  const data = await WatchlistService.getWatchlist(userId);

  return ApiResponse.success(res, { success: true, ...data }, "Alert toggled");
});

exports.deleteAlert = asyncHandler(async (req, res) => {
  const userId = req.user?.id;
  const { id } = req.params;

  await WatchlistService.deleteAlert({ userId, alertId: id });
  const data = await WatchlistService.getWatchlist(userId);

  return ApiResponse.success(res, { success: true, ...data }, "Alert deleted");
});

// ─── Lists ───────────────────────────────────────────────────

exports.createList = asyncHandler(async (req, res) => {
  const userId          = req.user?.id;
  const { name, iconKey } = req.body;

  if (!name) return ApiResponse.error(res, "name is required", 400);

  await WatchlistService.createList({ userId, name, iconKey });
  const data = await WatchlistService.getWatchlist(userId);

  return ApiResponse.success(res, { success: true, ...data }, "List created");
});