import { NextRequest, NextResponse } from "next/server";
import { createCategoriesSchema } from "@/lib/zodSchemas";
import { authOptions } from "@/app/api/auth/[...nextauth]/auth-options";
import { getServerSession } from "next-auth";
import db from "@/lib/db";
import { CategoryType, Prisma, UserRole } from "@prisma/client";
import { getLogger } from "@/utils/logger";

const logger = getLogger("/api/review")


export const POST = async (req: Request) => {
    try {
        const data = await req.json()

        const variant_id = data.variant_id
        const review = data.review
        const rating = data.rating

        if (!variant_id || !review || !rating) {
            return NextResponse.json({ mssg: "Variant ID, review and rating are required" }, { status: 400 });
        }

        const session = await getServerSession(authOptions);

        if (!session?.user.uuid) {
            return NextResponse.json({mssg: "Login first"}, {status: 404})
        }

        const user = await db.user.findUnique({
            where: {
                uuid: session?.user.uuid
            }, 
            include: {
                profile: true
            }
        })
        const profile = user?.profile;

        if (!profile) {
            return NextResponse.json({ mssg: "Profile not found" }, { status: 404 });
        }

        const reviewExists = await db.review.findFirst({
            where: {
                variant_id: variant_id,
                profile_id: profile.id
            }
        })

        if (reviewExists){
            return NextResponse.json({mssg: "Review already exist!"}, {status: 404})
        }

        const reviews = await db.review.create({
            data: {
                review: review,
                rating: rating,
                profile_id: profile.id,
                variant_id: variant_id,
            },
            include: {
                profile: true,
            }
        })

        // console.log(reviews)

        return NextResponse.json({ mssg: "Review created successfully", reviews }, { status: 200 })

    }
    catch (error:any) { 
        logger.error("Failed to add a review", {
            error: error?.config?.data ?? error?.message ?? "Unknown error"
        })

        return new Response("Internal Server Error", { status: 500 });
    }
}