import { Request, Response } from "express";
import Event from "../../models/event";
import { isValidObjectId } from "mongoose";
import Product from "../../models/product";
import storeInformation from "../../models/storeInformation";
import { toImageUrl, toImageUrls } from "../../utils/imageUrl";

const getEventDetails = async (req: Request, res: Response) => {
  const { id } = req.params;

  if (!isValidObjectId(id)) {
    return res.status(400).json({
      message: "Event ID is not valid",
    });
  }

  try {
    const event: any = await Event.findOne({
      _id: id,
      isDeleted: { $ne: true },
    }).lean();

    if (!event) {
      return res.status(404).json({ message: "Event not found" });
    }

    // .lean() also skips the Occasion icon transform.
    const occ: any = event.occasion ?? null;
    event.occasion = occ;
    if (occ?.icon) occ.icon = toImageUrl(occ.icon);

    for (const [giftIndex, gift] of event.gifts.entries()) {
      const product = await Product.findById(gift.product);
      const store = await storeInformation.findOne({
        vendorID: product.vendor._id,
      });
      event.gifts[giftIndex].product.storeInfo = store;

      // .lean() bypasses the Product schema's toJSON transform, so the
      // stored S3 key needs to be expanded into a full URL manually here.
      const giftProduct: any = event.gifts[giftIndex].product;
      if (giftProduct?.images) {
        giftProduct.images = toImageUrls(giftProduct.images);
      }
    }

    res.status(200).json(event);
  } catch (err) {
    res.status(500).json({ message: err });
  }
};

export { getEventDetails };
