import { NextResponse } from "next/server"; import dbConnect from "@/lib/mongodb"; import Cart from "@/models/Cart"; import { verifyToken } from "@/lib/auth"; export async function GET(request) { try { const token = request.headers.get("authorization")?.split(" ")[1]; if (!token) { return NextResponse.json([]); } const decoded = verifyToken(token); await dbConnect(); const cartItems = await Cart.find({ userId: decoded.userId }).populate( "productId" ); return NextResponse.json(cartItems); } catch (error) { return NextResponse.json([]); } } export async function POST(request) { try { const token = request.headers.get("authorization")?.split(" ")[1]; if (!token) { return NextResponse.json({ error: "未登录" }, { status: 401 }); } const decoded = verifyToken(token); const { productId, quantity } = await request.json(); await dbConnect(); // 检查购物车是否已存在该商品 let cartItem = await Cart.findOne({ userId: decoded.userId, productId: productId, }); if (cartItem) { // 如果存在,更新数量 cartItem.quantity += quantity; await cartItem.save(); } else { // 如果不存在,创建新的购物车项 cartItem = await Cart.create({ userId: decoded.userId, productId: productId, quantity: quantity, }); } return NextResponse.json({ message: "添加成功", cartItem }); } catch (error) { return NextResponse.json({ error: "添加失败" }, { status: 500 }); } } export async function DELETE(request) { try { const token = request.headers.get("authorization")?.split(" ")[1]; if (!token) { return NextResponse.json({ error: "未登录" }, { status: 401 }); } const decoded = verifyToken(token); const { cartItemId } = await request.json(); await dbConnect(); await Cart.findByIdAndDelete(cartItemId); return NextResponse.json({ message: "删除成功" }); } catch (error) { return NextResponse.json({ error: "删除失败" }, { status: 500 }); } } export async function PUT(request) { try { const token = request.headers.get("authorization")?.split(" ")[1]; if (!token) { return NextResponse.json({ error: "未登录" }, { status: 401 }); } const decoded = verifyToken(token); const { cartItemId, quantity } = await request.json(); await dbConnect(); const cartItem = await Cart.findById(cartItemId); if (!cartItem) { return NextResponse.json({ error: "购物车商品不存在" }, { status: 404 }); } cartItem.quantity = quantity; await cartItem.save(); return NextResponse.json({ message: "更新成功", cartItem }); } catch (error) { return NextResponse.json({ error: "更新失败" }, { status: 500 }); } }