import { NextRequest, NextResponse } from 'next/server';
import dbConnect from '../../src/lib/mongodb';
import Cart from '../../src/models/Cart';
import ProductSKU from '../../src/models/ProductSKU';

export async function GET(request: NextRequest, context?: { params: Promise<any> }) {
  try {
    await dbConnect();
    const { searchParams } = new URL(request.url);
    const user = searchParams.get('user');
    if (!user) return NextResponse.json({ success: false, error: 'User id required' }, { status: 400 });

    const cart = await Cart.findOne({ user }).populate('items.sku items.product');
    if (!cart) return NextResponse.json({ success: true, data: { items: [] } });
    return NextResponse.json({ success: true, data: cart });
  } catch (err: any) {
    console.error('Cart GET error', err);
    return NextResponse.json({ success: false, error: err.message || 'Failed to fetch cart' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    await dbConnect();
    const body = await request.json();
    const { user, productId, skuId, quantity = 1 } = body;
    if (!user || !skuId || !productId) return NextResponse.json({ success: false, error: 'user, productId and skuId required' }, { status: 400 });

    const sku = await ProductSKU.findById(skuId);
    if (!sku) return NextResponse.json({ success: false, error: 'SKU not found' }, { status: 404 });

    let cart = await Cart.findOne({ user });
    if (!cart) {
      cart = new Cart({ user, items: [] });
    }

    const existing = cart.items.find((i: any) => String(i.sku) === String(skuId));
    if (existing) {
      existing.quantity += quantity;
      existing.price = sku.price;
    } else {
      cart.items.push({ sku: skuId, product: productId, quantity, price: sku.price });
    }

    await cart.save();
    return NextResponse.json({ success: true, data: cart });
  } catch (err: any) {
    console.error('Cart POST error', err);
    return NextResponse.json({ success: false, error: err.message || 'Failed to add to cart' }, { status: 500 });
  }
}

export async function PUT(request: NextRequest, context?: { params: Promise<any> }) {
  try {
    await dbConnect();
    const body = await request.json();
    const { user, skuId, quantity } = body;
    if (!user || !skuId || typeof quantity !== 'number') return NextResponse.json({ success: false, error: 'user, skuId and quantity required' }, { status: 400 });

    const cart = await Cart.findOne({ user });
    if (!cart) return NextResponse.json({ success: false, error: 'Cart not found' }, { status: 404 });

    const item = cart.items.find((i: any) => String(i.sku) === String(skuId));
    if (!item) return NextResponse.json({ success: false, error: 'Item not found' }, { status: 404 });

    item.quantity = quantity;
    await cart.save();
    return NextResponse.json({ success: true, data: cart });
  } catch (err: any) {
    console.error('Cart PUT error', err);
    return NextResponse.json({ success: false, error: err.message || 'Failed to update cart' }, { status: 500 });
  }
}

export async function DELETE(request: NextRequest, context?: { params: Promise<any> }) {
  try {
    await dbConnect();
    const body = await request.json();
    const { user, skuId } = body;
    if (!user || !skuId) return NextResponse.json({ success: false, error: 'user and skuId required' }, { status: 400 });

    const cart = await Cart.findOne({ user });
    if (!cart) return NextResponse.json({ success: false, error: 'Cart not found' }, { status: 404 });

    cart.items = cart.items.filter((i: any) => String(i.sku) !== String(skuId));
    await cart.save();
    return NextResponse.json({ success: true, data: cart });
  } catch (err: any) {
    console.error('Cart DELETE error', err);
    return NextResponse.json({ success: false, error: err.message || 'Failed to remove item' }, { status: 500 });
  }
}
