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/checkout/deliveryCost/[uuid]');

export const GET = async (req: NextRequest, { params }: { params: { uuid: string } }) => {
    try {
        const session = await getServerSession(authOptions);
        if (!session?.user.uuid) {
            return NextResponse.json({ mssg: "You are not authorized !" }, { status: 403 });
        }

        // console.log(params.uuid)

        const address = await db.address.findUnique({
            where: {
                uuid: params.uuid
            },
            include: {
                shipping_zone: true,
                profile: true
            }
        });

        // console.log(address)

        const cart = await db.cart.findUnique({
            where: {
                profile_id: address?.profile_id
            },
            include: {
                CartItem: {
                    include: {
                        variant: true
                    }
                }
            }
        })

        // console.log(cart)
        var totalWeight = 0;

        cart?.CartItem.forEach((item) => {
            totalWeight += item.variant.weight * item.quantity
        })

        var totalCost = 0;

        if (totalWeight > 1) {
            totalCost = (address?.shipping_zone?.delivery_cost ?? 0) + (address?.shipping_zone?.per_kg_cost ?? 0) * (totalWeight - 1);
        }

        // console.log("Total Cost", totalCost)

        return NextResponse.json({
            mssg: totalCost
        }, { status: 200, })

    }
    catch (error: any) {
        logger.error("Failed to fetch delivery cost data", {
            error: error?.config?.data ?? error?.message ?? "Unknown error"
        });
        return NextResponse.json({ mssg: "Internal server error" }, { status: 500 });
    }
} 