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

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 wl = await Wishlist.findOne({ user }).populate('products');
    if (!wl) return NextResponse.json({ success: true, data: { products: [] } });
    return NextResponse.json({ success: true, data: wl });
  } catch (err: any) {
    console.error('Wishlist GET error', err);
    return NextResponse.json({ success: false, error: err.message || 'Failed to fetch wishlist' }, { status: 500 });
  }
}

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

    let wl = await Wishlist.findOne({ user });
    if (!wl) {
      wl = new Wishlist({ user, products: [] });
    }
    if (!wl.products.map(String).includes(String(productId))) {
      wl.products.push(productId);
      await wl.save();
    }
    return NextResponse.json({ success: true, data: wl });
  } catch (err: any) {
    console.error('Wishlist POST error', err);
    return NextResponse.json({ success: false, error: err.message || 'Failed to add to wishlist' }, { status: 500 });
  }
}

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

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

    wl.products = wl.products.filter((p: any) => String(p) !== String(productId));
    await wl.save();
    return NextResponse.json({ success: true, data: wl });
  } catch (err: any) {
    console.error('Wishlist DELETE error', err);
    return NextResponse.json({ success: false, error: err.message || 'Failed to remove from wishlist' }, { status: 500 });
  }
}
