import {  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/question")


export const POST = async (req: Request) => {
    try {
        const data = await req.json()

        const variant_id = data.variant_id
        const ques = data.question

        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 question = await db.question.create({
            data: {
                question: ques,
                profile_id: profile.id,
                variant_id: variant_id,
            },
            include: {
                profile: true,
            }
        })

        // console.log(question)

        return NextResponse.json({ mssg: "Question created successfully", question }, { status: 200 })

    }
    catch (error: any) {
        logger.error("Failed to add a question", {
            error: error?.config?.data ?? error?.message ?? "Unknown error"
        });
        return new Response("Internal Server Error", { status: 500 });
    }
}