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

export async function GET(request: NextRequest) {
  try {
    await dbConnect();

    const { searchParams } = new URL(request.url);

    const user_id = searchParams.get("user_id");
    const guest_id = searchParams.get("guest_id");

    if (!user_id && !guest_id) {
      return NextResponse.json(
        {
          success: false,
          error: "user_id or guest_id is required",
        },
        { status: 400 }
      );
    }

    const query = user_id
      ? { user_id }
      : { guest_id };

    const wishlist = await Wishlist.find(query)
      .populate({
        path: "product_id",
      })
      .sort({ createdAt: -1 });

    return NextResponse.json({
      success: true,
      count: wishlist.length,
      data: wishlist,
    });
  } 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_id,
      guest_id,
      product_id,
    } = body;

    if (!product_id) {
      return NextResponse.json(
        {
          success: false,
          error: "product_id is required",
        },
        { status: 400 }
      );
    }

    if (!user_id && !guest_id) {
      return NextResponse.json(
        {
          success: false,
          error: "user_id or guest_id is required",
        },
        { status: 400 }
      );
    }

    const existingWishlistItem = await Wishlist.findOne(
      user_id
        ? {
            user_id,
            product_id,
          }
        : {
            guest_id,
            product_id,
          }
    );

    if (existingWishlistItem) {
      return NextResponse.json({
        success: true,
        message: "Product already exists in wishlist",
        data: existingWishlistItem,
      });
    }

    const wishlistItem = await Wishlist.create({
      user_id: user_id || null,
      guest_id: guest_id || null,
      product_id,
    });

    const populatedItem = await Wishlist.findById(
      wishlistItem._id
    ).populate("product_id");

    return NextResponse.json(
      {
        success: true,
        message: "Product added to wishlist",
        data: populatedItem,
      },
      { status: 201 }
    );
  } catch (err: any) {
    console.error("Wishlist POST error:", err);

    if (err.code === 11000) {
      return NextResponse.json(
        {
          success: false,
          error: "Product already exists in wishlist",
        },
        { status: 409 }
      );
    }

    return NextResponse.json(
      {
        success: false,
        error: err.message || "Failed to add product to wishlist",
      },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    await dbConnect();

    const body = await request.json();

    const {
      user_id,
      guest_id,
      product_id,
    } = body;

    if (!product_id) {
      return NextResponse.json(
        {
          success: false,
          error: "product_id is required",
        },
        { status: 400 }
      );
    }

    if (!user_id && !guest_id) {
      return NextResponse.json(
        {
          success: false,
          error: "user_id or guest_id is required",
        },
        { status: 400 }
      );
    }

    const deletedWishlistItem = await Wishlist.findOneAndDelete(
      user_id
        ? {
            user_id,
            product_id,
          }
        : {
            guest_id,
            product_id,
          }
    );

    if (!deletedWishlistItem) {
      return NextResponse.json(
        {
          success: false,
          error: "Wishlist item not found",
        },
        { status: 404 }
      );
    }

    return NextResponse.json({
      success: true,
      message: "Product removed from wishlist",
    });
  } catch (err: any) {
    console.error("Wishlist DELETE error:", err);

    return NextResponse.json(
      {
        success: false,
        error: err.message || "Failed to remove product from wishlist",
      },
      { status: 500 }
    );
  }
}