import { auth } from "@/auth";
import { db } from "@/lib/db";
import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest) {
  const session = await auth();
  if (!session?.user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const q = req.nextUrl.searchParams.get("q")?.trim() ?? "";
  if (q.length < 2) return NextResponse.json([]);

  const products = await db.product.findMany({
    where: {
      isActive: true,
      OR: [
        { name: { contains: q, mode: "insensitive" } },
        { code: { contains: q, mode: "insensitive" } },
        { description: { contains: q, mode: "insensitive" } },
      ],
    },
    select: {
      id: true,
      code: true,
      name: true,
      description: true,
      lastPrice: true,
      vendorPrices: {
        select: {
          price: true,
          updatedAt: true,
          vendor: { select: { id: true, name: true } },
        },
        orderBy: { updatedAt: "desc" },
      },
    },
    take: 10,
    orderBy: { name: "asc" },
  });

  return NextResponse.json(
    products.map((p) => ({
      id: p.id,
      code: p.code,
      name: p.name,
      description: p.description,
      lastPrice: p.lastPrice != null ? Number(p.lastPrice) : null,
      vendorPrices: p.vendorPrices.map((vp) => ({
        vendorId: vp.vendor.id,
        vendorName: vp.vendor.name,
        price: Number(vp.price),
      })),
    }))
  );
}
