import { NextRequest, NextResponse } from "next/server";
import db from "@/lib/db";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/auth-options";
import { UserRole } from "@prisma/client";
import { getLogger } from "@/utils/logger";


const logger = getLogger("/api/admin/product/[productId]")


export const GET = async (req: NextRequest, { params }: { params: { productId: string } }) => {
    try {

        const {searchParams} = new URL(req.url)
        const page = parseInt(searchParams.get("page") || "1")
        const limit = parseInt(searchParams.get("limit") || "10")

        const session = await getServerSession(authOptions);
        if (!session || session.user.role !== UserRole.ADMIN) {
            return new NextResponse("Forbidden", { status: 403 });
        }   

        const variants = await db.productVariant.findMany({
            where: {
                product_id: parseInt(params.productId as string),
            },
            include: {
                variant_images: true
            }
        })

        const totalCount = await db.productVariant.count({
            where: {
                product_id: parseInt(params.productId as string),
            }
        })

        return NextResponse.json({variants: variants, page: page, limit: limit, total: totalCount}, {status: 200})

    }
    catch (error:any) {

        logger.error(`Failed to fetch variants of product with ID: ${params.productId}`, {
            error: error?.config?.data ?? error?.message ?? "Unknown error"
        })
        
        return new NextResponse("Internal Server Error", { status: 500 });
    }

}