import { NextRequest, NextResponse } from "next/server";
import db from "@/lib/db";
import { authOptions } from "@/app/api/auth/[...nextauth]/auth-options";
import { getServerSession } from "next-auth";
import { getLogger } from "@/utils/logger";

const logger = getLogger("/api/orders/[uuid]")

export const GET = async (request: NextRequest, { params }: { params: { uuid: string } }) => {
    const { uuid } = params;

    try {
        const session = await getServerSession(authOptions);
        if (!session) {
            return NextResponse.json({ mssg: "You are not authorized !" }, { status: 403 });
        }

        const user = await db.user.findUnique({
            where: {
                uuid: session.user.uuid
            },
            include: {
                profile: true
            }
        })


        const order = await db.orders.findUnique({
            where: {
                uuid: params.uuid
            },
            include: {
                shipment_details: true,
                order_items: {
                    include: {
                        variant: {
                            include: {
                                variant_images: true
                            }
                        }
                    }
                },
                address: {
                    include: {
                        shipping_zone: true
                    }
                },
                payment: true,

            }
        })

        if (!order) {
            return NextResponse.json({ mssg: "Order not found" }, { status: 404 });
        }

        if (order?.profile_id !== user?.profile?.id) {
            return NextResponse.json({ mssg: "You are not authorized to view this order" }, { status: 403 });
        }

        return NextResponse.json({ data: order }, { status: 200 })


    }
    catch (error: any) {
        logger.error(`Failed to fetch an order of uuid ${uuid}`, {
            error: error?.config?.data ?? error?.message ?? "Unknown error"
        });

        return new Response("Failed to fetch order", { status: 500 });
    }


}