import { NextRequest, NextResponse } from 'next/server';
import dbConnect from '../../lib/mongodb';
import Cart from '../../models/Cart';
import Colors from '../../models/Color';
import Sizes from '../../models/Size';
import ProductSKU from '../../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");
    const guestId = searchParams.get("guestId");

    if (!user && !guestId) {
      return NextResponse.json(
        {
          success: false,
          error: "User id or guest ID required",
        },
        { status: 400 }
      );
    }

    const query = user ? { user } : { guestId };

    const cart = await Cart.findOne(query)
      .populate({
        path: "items.sku",
        select: "sku color size quantity price comparePrice",
        populate: [
          {
            path: "color",
            select: "name",
          },
          {
            path: "size",
            select: "name",
          },
        ],
      })
      .populate({
        path: "items.product",
        select:
          "name slug price defaultImage description shortDescription category subcategory",
      });

    if (!cart) {
      return NextResponse.json({
        success: true,
        data: {
          items: [],
        },
      });
    }

    const cartData = cart.toObject();

    cartData.items = cartData.items.map((item: any) => ({
      ...item,
      sku: item.sku
        ? {
            ...item.sku,
            color: item.sku.color?.name || null,
            size: item.sku.size?.name || null,
          }
        : null,
    }));

    return NextResponse.json({
      success: true,
      data: cartData,
    });
  } 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, guestId, productId, skuId, quantity = 1 } = body;
   if ((!user && !guestId) || !skuId || !productId)return NextResponse.json({ success: false, error: 'user, guestId, 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 });

    const query = user
    ? { user }
    : { guestId };

    let cart = await Cart.findOne(query);
    if (!cart) {
      cart = new Cart({
        user: user || null,
        guestId: guestId || null,
        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, guestId, skuId, quantity } = body;
    if ((!user && !guestId) || !skuId || typeof quantity !== 'number') return NextResponse.json({ success: false, error: 'user, guestId, skuId and quantity required' }, { status: 400 });

    const query = user
    ? { user }
    : { guestId };

    const cart = await Cart.findOne(query);
    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, guestId, skuId } = body;

    if (!user && !guestId) {
      return NextResponse.json(
        {
          success: false,
          error: 'user or guestId required',
        },
        { status: 400 }
      );
    }

    const query = user
      ? { user }
      : { guestId };

    const cart = await Cart.findOne(query);

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

    // Clear entire cart
    if (!skuId) {
      cart.items = [];
      await cart.save();

      return NextResponse.json({
        success: true,
        message: 'Cart cleared successfully',
        data: cart,
      });
    }

    // Remove single item
    cart.items = cart.items.filter(
      (i: any) => String(i.sku) !== String(skuId)
    );

    await cart.save();

    return NextResponse.json({
      success: true,
      message: 'Item removed successfully',
      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 }
    );
  }
}
