import { NextResponse } from "next/server";
import { getCollection } from "@/lib/mongodb";

// GET - Fetch featured products
export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const limit = parseInt(searchParams.get("limit") || "8");
    const collection = await getCollection("ecommers");

    // Fetch featured products from ecommers collection
    const featuredProducts = await collection
      .find({ 
        featured: true, 
        active: true 
      })
      .sort({ createdAt: -1 })
      .limit(limit)
      .toArray();

    // If not enough featured products, get latest products
    if (featuredProducts.length < limit) {
      const latestProducts = await collection
        .find({ active: true })
        .sort({ createdAt: -1 })
        .limit(limit - featuredProducts.length)
        .toArray();
      
      featuredProducts.push(...latestProducts);
    }

    // Convert _id to string and remove duplicates
    const uniqueProducts = featuredProducts
      .slice(0, limit)
      .map((product) => ({
        ...product,
        _id: product._id.toString(),
      }));

    return NextResponse.json({ products: uniqueProducts });
  } catch (error) {
    console.error("Error fetching featured products:", error);
    return NextResponse.json(
      { error: "Failed to fetch featured products" },
      { status: 500 }
    );
  }
}
