import { NextRequest, NextResponse } from "next/server";
import { db, users, userBlocks, eq, and, or, ne, ilike, isNotNull } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";

export async function GET(req: NextRequest) {
  const { session, response } = await requireSession();
  if (response) return response;

  const q = req.nextUrl.searchParams.get("q")?.trim().slice(0, 50) ?? "";
  if (q.length < 2) return NextResponse.json({ users: [] });

  const blocked = await db
    .select({ blockedId: userBlocks.blockedId })
    .from(userBlocks)
    .where(eq(userBlocks.blockerId, session!.user.id));
  const blockedByMe = new Set(blocked.map((b) => b.blockedId));

  const blockedMe = await db
    .select({ blockerId: userBlocks.blockerId })
    .from(userBlocks)
    .where(eq(userBlocks.blockedId, session!.user.id));
  const haveBlockedMe = new Set(blockedMe.map((b) => b.blockerId));

  const rows = await db
    .select({
      id: users.id,
      name: users.name,
      username: users.username,
      avatarUrl: users.avatarUrl,
      bio: users.bio,
    })
    .from(users)
    .where(
      and(
        isNotNull(users.username),
        ne(users.id, session!.user.id),
        eq(users.isPrivate, false),
        or(ilike(users.name, `%${q}%`), ilike(users.username, `%${q}%`))
      )
    )
    .limit(20);

  const filtered = rows.filter((u) => !blockedByMe.has(u.id) && !haveBlockedMe.has(u.id));

  return NextResponse.json({ users: filtered });
}
