import { NextResponse } from "next/server";
import { z } from "zod";
import { auth } from "@/auth";
import { matchPeople, suggestTeam } from "@/lib/match";

const Body = z.object({
  query: z.string().min(2).max(4000),
  offices: z.array(z.enum(["DUBLIN", "BOSTON", "VANCOUVER", "REMOTE"])).optional(),
  departments: z.array(z.string()).optional(),
  preferAvailable: z.boolean().optional(),
  teamSize: z.number().int().min(1).max(12).optional(),
  limit: z.number().int().min(1).max(100).optional(),
});

/** POST /api/match – JSON API for the fit search (used by integrations / Slack bots later). */
export async function POST(req: Request) {
  const session = await auth();
  if (!session?.user) return NextResponse.json({ error: "unauthenticated" }, { status: 401 });
  const parsed = Body.safeParse(await req.json().catch(() => null));
  if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
  const { teamSize, ...opts } = parsed.data;
  const results = await matchPeople(opts);
  return NextResponse.json({ team: suggestTeam(results, teamSize ?? 5), results });
}
