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 getEvents = async (req: Request, res: Response) => {
  const { page = 1, perPage = 10 } = req.query;
  const { id } = req.params;

  if (!isValidObjectId(id)) {
    return res.status(400).json({
      message: "User ID is not valid",
    });
  }

  try {
    const filter = {
      user: id,
      isDeleted: { $ne: true },
    };
    const [events, totalItemCount] = await Promise.all([
      Event.find(filter)
        .skip((Number(page) - 1) * Number(perPage))
        .limit(Number(perPage))
        .lean(),
      Event.countDocuments(filter),
    ]);
    for (const [index, event] of events.entries()) {
      // .lean() also skips the Occasion icon transform.
      const occ: any = (events[index] as any).occasion ?? null;
      (events[index] as any).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,
        });
        events[index].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 = events[index].gifts[giftIndex].product;
        if (giftProduct?.images) {
          giftProduct.images = toImageUrls(giftProduct.images);
        }
      }
    }

    res.status(200).json({ events, totalItemCount });
  } catch (err) {
    res.status(500).json({ message: err });
  }
};

export { getEvents };
