import { NextResponse } from "next/server";
import { getCollection } from "@/lib/mongodb";

// Function to escape special regex characters
function escapeRegExp(string: string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const search = searchParams.get("search") || "";
    const page = parseInt(searchParams.get("page") || "1", 10);
    const requestedLimit = parseInt(searchParams.get("limit") || "50", 10);
    const limit = Math.min(Math.max(requestedLimit, 1), 1000); // Limit between 1 and 1000
    const skip = (page - 1) * limit;

    const productsCollection = await getCollection<any>("products");

    // Build search query
    const query: any = {};
    if (search.trim()) {
      // Escape special regex characters to prevent errors
      const escapedSearch = escapeRegExp(search.trim());
      query.$or = [
        { title: { $regex: escapedSearch, $options: "i" } },
        { sku: { $regex: escapedSearch, $options: "i" } },
        { bcode1: { $regex: escapedSearch, $options: "i" } },
        { description: { $regex: escapedSearch, $options: "i" } },
        { scat: { $regex: escapedSearch, $options: "i" } },
        { cat: { $regex: escapedSearch, $options: "i" } },
        { itc1: { $regex: escapedSearch, $options: "i" } },
        { itn: { $regex: escapedSearch, $options: "i" } },
        { itc: { $regex: escapedSearch, $options: "i" } },
        { category: { $regex: escapedSearch, $options: "i" } },
        { supplier: { $regex: escapedSearch, $options: "i" } },
      ];
    }

    const [products, total] = await Promise.all([
      productsCollection
        .find(query)
        .skip(skip)
        .limit(limit)
        .toArray(),
      productsCollection.countDocuments(query),
    ]);

    return NextResponse.json({
      products: products.map((p: any) => ({
        ...p,
        _id: p._id?.toString() || p._id,
      })),
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error("Error fetching products:", error);
    return NextResponse.json(
      { 
        error: "Failed to fetch products",
        details: error instanceof Error ? error.message : "Unknown error"
      },
      { status: 500 }
    );
  }
}

