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

/* Public institution lookup for the /apply page (online admission):
   - ?code=XXXX → one ACTIVE institution + the classes it operates
   - ?q=name    → ACTIVE institutions matching the name (picker list) */

export async function GET(req: Request) {
  const url = new URL(req.url);
  const code = (url.searchParams.get("code") ?? "").trim().toUpperCase();
  const q = (url.searchParams.get("q") ?? "").trim();

  if (code) {
    const institution = await prisma.institution.findUnique({
      where: { code },
      select: {
        name: true, code: true, type: true, status: true, address: true,
        district: true, subDistrict: true, eiin: true, logo: true,
        admissionFeeEnabled: true, admissionFeeAmount: true,
        academicSelections: {
          where: { academicItem: { category: { in: ["CLASS", "SESSION"] }, isActive: true } },
          select: { academicItem: { select: { id: true, name: true, nameBn: true, category: true } } },
          orderBy: { academicItem: { id: "asc" } },
        },
        // where the applicant pays — the admin-maintained receiving accounts
        collectionAccounts: {
          where: { isActive: true },
          select: {
            type: true, provider: true, accountType: true, label: true,
            accountName: true, accountNumber: true, branch: true, note: true,
          },
          orderBy: [{ sortOrder: "asc" }, { id: "asc" }],
        },
      },
    });
    if (!institution || institution.status !== "ACTIVE") {
      return NextResponse.json({ institution: null }, { status: 404 });
    }

    return NextResponse.json({
      institution: {
        name: institution.name,
        code: institution.code,
        type: institution.type,
        address: institution.address,
        district: institution.district,
        subDistrict: institution.subDistrict,
        eiin: institution.eiin,
        logo: institution.logo,
        classes: institution.academicSelections
          .filter((s) => s.academicItem.category === "CLASS")
          .map((s) => s.academicItem),
        sessions: institution.academicSelections
          .filter((s) => s.academicItem.category === "SESSION")
          .map((s) => s.academicItem)
          .reverse(), // newest session first
        admissionFee: {
          enabled: institution.admissionFeeEnabled && Number(institution.admissionFeeAmount) > 0,
          amount: Number(institution.admissionFeeAmount),
        },
        paymentAccounts: institution.collectionAccounts,
      },
    });
  }

  if (q.length < 2) return NextResponse.json({ institutions: [] });

  const institutions = await prisma.institution.findMany({
    where: {
      status: "ACTIVE",
      parentId: null,
      OR: [{ name: { contains: q } }, { code: { contains: q } }],
    },
    select: { name: true, code: true, type: true, district: true, subDistrict: true },
    orderBy: { name: "asc" },
    take: 20,
  });
  return NextResponse.json({ institutions });
}
