import { NextRequest, NextResponse } from "next/server";
import { authOptions } from "@/app/api/auth/[...nextauth]/auth-options";
import { getServerSession } from "next-auth";
import db from "@/lib/db";
import { getLogger } from "@/utils/logger";


const logger = getLogger("/api/wishlist")

export const POST = async (request: NextRequest) => {
    try {

        const session = await getServerSession(authOptions);

        if (!session?.user.uuid) {
            return NextResponse.json({ mssg: "Login first" }, { status: 403 })
        }

        const user = await db.user.findUnique({
            where: {
                uuid: session.user.uuid
            },
            include: {
                profile: true
            }
        })

        if (user?.profile?.id === undefined) {
                return NextResponse.json({ mssg: "User profile not found" }, { status: 404 });
            }


        const req = await request.json()

        const variantUUID = req.variantUUID

        if (!variantUUID) {
            return NextResponse.json({ mssg: "variantUUID is required" }, { status: 400 });
        }

        const variant = await db.productVariant.findUnique({
            where: {
                uuid: variantUUID
            }
        })

        if (!variant) {
            return NextResponse.json({mssg: "Variant not found"}, {status:404})
        }

        var wishlist = await db.wishlist.findUnique({
            where: {
                profile_id: user?.profile?.id
            }
        })

        if (!wishlist){
            
            wishlist = await db.wishlist.create({
                data: {
                    profile_id: user.profile.id
                }
            })
        }
        
        const wishlistItemExists = await db.wishListItem.findUnique({
            where: {
                wishlist_id_variant_id: {
                    wishlist_id: wishlist.id,
                    variant_id: variant.id
                }
            }
        })

        if (wishlistItemExists){
            return NextResponse.json({mssg: "Item's already in wishlist"}, {status: 404})
        }

        await db.wishListItem.create({
            data: {
                variant: { connect: { id: variant.id } },
                wishlist: { connect: { id: wishlist.id } }
            }
        })

        wishlist = await db.wishlist.findUnique({
            where: {
                profile_id: user.profile.id,
            },
            include: {
                WishListItem: {
                    include: {
                        variant: {
                            include: {
                                variant_images: true
                            }
                        }
                    }
                }
            }
        })

        return NextResponse.json({mssg: "Item has been added to wishlist", wishlist}, {status: 200})

    }
    catch (error: any) {
        logger.error("Failed to search update wishlist", {
            error: error?.config?.data ?? error?.message ?? "Unknown error"
        })

        return new NextResponse("Internal server error", { status: 500 })
    }
}



export const GET = async (request: NextRequest) => {
    try{
        const session = await getServerSession(authOptions);

        if (!session?.user.uuid) {
            return NextResponse.json({ mssg: "Login first" }, { status: 403 })
        }

        const user = await db.user.findUnique({
            where: {
                uuid: session.user.uuid
            },
            include: {
                profile: true
            }
        })

        if (user?.profile?.id === undefined) {
                return NextResponse.json({ mssg: "User profile not found" }, { status: 404 });
            }

        var wishlist = await db.wishlist.findUnique({
            where: {
                profile_id: user.profile.id,
            },
            include: {
                WishListItem: {
                    include: {
                        variant: {
                            include: {
                                variant_images: true
                            }
                        }
                    }
                }
            }
        })

        if (!wishlist){
            wishlist = await db.wishlist.create({
                data: {
                    profile_id: user.profile.id,
                },
                include: {
                    WishListItem: {
                        include: {
                            variant: {
                                include: {
                                    variant_images: true
                                }
                            }
                        }
                    }
                }
            })
        }

        return NextResponse.json(wishlist, {status: 200})
    }
    catch(error:any) {
        
        logger.error("Failed to fetch wishlist", {
            error: error?.config?.data ?? error?.message ?? "Unknown error"
        })
        return new NextResponse("Internal server error", {status: 500})
    }
}