const List = require("../models/list.model");
const { isValidItemType, isValidItemGroup, isValidZone } = require("../constants/classifications");
const { sendError } = require("../utils/http");
const { logError } = require("../utils/logger");


exports.getList = async (req, res) => {
  const items = await List.getUnboughtItems();
  res.json(items);
};

exports.getItemByName = async (req, res) => {
  const { itemName } = req.query;
  const item = await List.getItemByName(itemName);
  res.json(item);
}


exports.addItem = async (req, res) => {
  const { itemName, quantity } = req.body;
  const userId = req.user.id;

  // Get processed image if uploaded
  const imageBuffer = req.processedImage?.buffer || null;
  const mimeType = req.processedImage?.mimeType || null;

  const id = await List.addOrUpdateItem(itemName, quantity, userId, imageBuffer, mimeType);

  await List.addHistoryRecord(id, quantity, userId);

  res.json({ message: "Item added/updated", addedBy: userId });
};


exports.markBought = async (req, res) => {
  const userId = req.user.id;
  const { id, quantity } = req.body;
  await List.setBought(id, userId, quantity);
  res.json({ message: "Item marked bought" });
};


exports.getSuggestions = async (req, res) => {
  const { query } = req.query || "";
  const suggestions = await List.getSuggestions(query);
  res.json(suggestions);
};

exports.getRecentlyBought = async (req, res) => {
  const items = await List.getRecentlyBoughtItems();
  res.json(items);
};

exports.updateItemImage = async (req, res) => {
  const { id, itemName, quantity } = req.body;
  const userId = req.user.id;

  // Get processed image
  const imageBuffer = req.processedImage?.buffer || null;
  const mimeType = req.processedImage?.mimeType || null;

  if (!imageBuffer) {
    return sendError(res, 400, "No image provided");
  }

  // Update the item with new image
  await List.addOrUpdateItem(itemName, quantity, userId, imageBuffer, mimeType);

  res.json({ message: "Image updated successfully" });
};

exports.getClassification = async (req, res) => {
  const { id } = req.params;
  const classification = await List.getClassification(id);
  res.json(classification);
};

exports.updateItemWithClassification = async (req, res) => {
  const { id } = req.params;
  const { itemName, quantity, classification } = req.body;
  const userId = req.user.id;

  try {
    // Update item name and quantity if changed
    if (itemName !== undefined || quantity !== undefined) {
      await List.updateItem(id, itemName, quantity);
    }

    // Update classification if provided
    if (classification) {
      const { item_type, item_group, zone } = classification;

      // Validate classification data
      if (item_type && !isValidItemType(item_type)) {
        return sendError(res, 400, "Invalid item_type");
      }

      if (item_group && !isValidItemGroup(item_type, item_group)) {
        return sendError(res, 400, "Invalid item_group for selected item_type");
      }

      if (zone && !isValidZone(zone)) {
        return sendError(res, 400, "Invalid zone");
      }

      // Upsert classification with confidence=1.0 and source='user'
      await List.upsertClassification(id, {
        item_type,
        item_group,
        zone: zone || null,
        confidence: 1.0,
        source: 'user'
      });
    }

    res.json({ message: "Item updated successfully" });
  } catch (error) {
    logError(req, "listsLegacy.updateItemWithClassification", error);
    sendError(res, 500, "Failed to update item");
  }
};
