import { Request, Response } from "express";
import { isValidObjectId } from "mongoose";
import Order from "../../models/order";
import { toImageUrl } from "../../utils/imageUrl";

const getWish = async (req: Request, res: Response) => {
  const { id } = req.params;

  if (!isValidObjectId(id)) {
    return res.status(400).json({ message: "Wish ID is not valid" });
  }

  try {
    const orderDoc = await Order.findById(id);

    if (!orderDoc) {
      return res.status(404).json({ message: "Wish not found" });
    }

    const order = orderDoc.toObject();
    const event = order.event;

    const gifts = (order.gifts || []).map((gift: any) => ({
      title: gift.product?.title,
      image: gift.product?.images?.[0] ? toImageUrl(gift.product.images[0]) : "",
      price: gift.price,
    }));

    // Prefer the occasion copied onto the order at checkout; fall back to the
    // event's (orders placed before occasions existed have none).
    const occ: any = order.occasion || event?.occasion || null;
    const occasion = occ
      ? {
          _id: occ._id,
          key: occ.key,
          title: occ.title,
          icon: occ.icon ? toImageUrl(occ.icon) : "",
        }
      : null;

    res.status(200).json({
      occasion,
      senderName: order.user?.name || "",
      recipientName: order.recipientName || "",
      eventTitle: event?.title || "",
      message: event?.note || "",
      eventDate: event?.fullDate || null,
      gifts,
    });
  } catch (err) {
    res.status(500).json({ message: err });
  }
};

export { getWish };
