import { NextResponse } from "next/server";

import { requireApiAccess } from "@/lib/authorization";
import { prisma } from "@/lib/prisma";

type SearchItem = {
  id: string;
  type: "LOT" | "PURCHASE";
  title: string;
  subtitle: string;
  href: string;
};

export async function GET(request: Request) {
  const auth = requireApiAccess(request);
  if (!auth.ok) return auth.response;

  const { searchParams } = new URL(request.url);
  const query = searchParams.get("q")?.trim() ?? "";

  if (query.length < 2) {
    return NextResponse.json({ data: [] satisfies SearchItem[] });
  }

  const [lots, purchases] = await Promise.all([
    prisma.inventoryLot.findMany({
      where: {
        OR: [
          { lotCode: { contains: query, mode: "insensitive" } },
          { purchase: { agent: { name: { contains: query, mode: "insensitive" } } } },
          { grade: { name: { contains: query, mode: "insensitive" } } },
          { warehouse: { name: { contains: query, mode: "insensitive" } } }
        ]
      },
      include: {
        purchase: {
          select: {
            agent: {
              select: {
                name: true
              }
            }
          }
        },
        grade: {
          select: {
            name: true
          }
        }
      },
      orderBy: [{ createdAt: "desc" }],
      take: 5
    }),
    prisma.purchase.findMany({
      where: {
        purchaseType: "REGULAR",
        OR: [
          { purchaseNo: { contains: query, mode: "insensitive" } },
          { agent: { name: { contains: query, mode: "insensitive" } } }
        ]
      },
      include: {
        agent: {
          select: {
            name: true
          }
        }
      },
      orderBy: [{ createdAt: "desc" }],
      take: 5
    })
  ]);

  const data: SearchItem[] = [
    ...lots.map((lot) => ({
      id: lot.id.toString(),
      type: "LOT" as const,
      title: lot.lotCode,
      subtitle: [lot.purchase?.agent?.name ?? "Pembelian bebas", lot.grade?.name ?? "-", lot.warehouseId ? "Lot persediaan" : null]
        .filter(Boolean)
        .join(" · "),
      href: `/lots/${lot.id.toString()}`
    })),
    ...purchases.map((purchase) => ({
      id: purchase.id.toString(),
      type: "PURCHASE" as const,
      title: purchase.purchaseNo,
      subtitle: [purchase.agent?.name ?? "Pembelian bebas", purchase.status].join(" · "),
      href: `/purchases?id=${purchase.id.toString()}`
    }))
  ];

  return NextResponse.json({ data });
}
