import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

/**
 * Public institution search for the login page's "Search Institution" modal —
 * members type their institution's name, pick it from the list and the
 * institution code fills into the login form. Active institutions only;
 * the code alone grants nothing (login still needs username + password).
 */
export async function GET(req: Request) {
  const q = (new URL(req.url).searchParams.get("q") ?? "").trim();
  if (q.length < 2) {
    return NextResponse.json({ institutions: [] });
  }

  const institutions = await prisma.institution.findMany({
    where: {
      status: "ACTIVE",
      OR: [{ name: { contains: q } }, { code: { contains: q.toUpperCase() } }],
    },
    select: { id: true, name: true, code: true, type: true, district: true, subDistrict: true },
    orderBy: [{ name: "asc" }],
    take: 8,
  });

  return NextResponse.json({ institutions });
}
