// @ts-nocheck
import { Request, Response } from 'express';
import asyncHandler from '../utils/asyncHandler';
import ApiError from '../utils/apiError';
import ApiResponse from '../utils/apiResponse';
import prisma from '../DB/db';

// --- Toggle Wishlist Item (Add/Remove) ---
export const toggleWishlist = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.params?.id;
  const { productId } = req.body;

  // 1. Ensure Wishlist Exists
  let wishlist = await prisma.wishlist.findUnique({ where: { userId } });
  if (!wishlist) {
    wishlist = await prisma.wishlist.create({ data: { userId: userId! } });
  }

  // 2. Check if item exists in wishlist
  const existingItem = await prisma.wishlistItem.findUnique({
    where: {
      wishlistId_productId: {
        wishlistId: wishlist.id,
        productId,
      },
    },
  });

  if (existingItem) {
    // Remove it
    await prisma.wishlistItem.delete({ where: { id: existingItem.id } });
    return res
      .status(200)
      .json(new ApiResponse(true, 200, 'Removed from wishlist', { added: false }));
  } else {
    // Add it
    await prisma.wishlistItem.create({
      data: {
        wishlistId: wishlist.id,
        productId,
      },
    });
    return res.status(200).json(new ApiResponse(true, 200, 'Added to wishlist', { added: true }));
  }
});

// --- Get My Wishlist ---
export const getMyWishlist = asyncHandler(async (req: Request, res: Response) => {
  const userId = req.params?.id;

  const wishlist = await prisma.wishlist.findUnique({
    where: { userId },
    include: {
      items: {
        include: {
          product: {
            include: {
              category: {
                select: { name: true, slug: true } // Fetch category for UI tags
              },
              variants: true, // Fetch variants for stock logic
            },
          },
        },
      },
    },
  });

  // Handle case where wishlist doesn't exist yet
  if (!wishlist) {
    return res.status(200).json(
      new ApiResponse(true, 200, "Wishlist fetched", { id: null, items: [] })
    );
  }



  // Return BOTH the Wishlist ID and the Items array
  return res.status(200).json(
    new ApiResponse(true, 200, "Wishlist fetched", wishlist)
  );
})


// delete wishlist
export const deleteWishlist = asyncHandler(async (req, res) => {
  const { id } = req.params;

  if (!id) {
    throw new ApiError(false, 400, 'Id id required');
  }

  const deleteList = await prisma.wishlistItem.delete({
    where: {
      id: id,
    },
  });


  res.status(200)
  .json(new ApiResponse(true,200,"wishlist removed successfully"))
});
