// ── Users: Search ────────────────────────────────────────────────────────────
// GET /api/users/search?q=  — Typeahead search users by name or email
//
// Auth: admin/super_admin only
// Returns up to 10 matching users, excluding the requester themselves.

import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"
import { avatarSvgUrl } from "@/lib/avatar"

// ── GET ──────────────────────────────────────────────────────────────────────

export async function GET(request: NextRequest) {
  try {
    const currentUser = await getSessionUser()
    if (!currentUser) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    if (currentUser.role !== "admin" && currentUser.role !== "super_admin") {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 })
    }

    const q = request.nextUrl.searchParams.get("q") || ""

    if (!q.trim()) {
      return NextResponse.json({ users: [] })
    }

    // Case-insensitive search on full name and email; exclude current user
    const result = await query(
      `SELECT id, first_name || ' ' || last_name AS name, email, avatar_url
       FROM users
       WHERE deleted_at IS NULL
         AND id != $1
         AND (LOWER(first_name || ' ' || last_name) LIKE LOWER($2)
              OR LOWER(email) LIKE LOWER($2))
       ORDER BY first_name ASC
       LIMIT 10`,
      [currentUser.id, `%${q}%`],
    )

    const users = result.rows.map((row: any) => ({
      id: row.id,
      name: row.name,
      email: row.email,
      avatar: avatarSvgUrl(row.name),
    }))

    return NextResponse.json({ users })
  } catch (error) {
    console.error("User search error:", error)
    return NextResponse.json({ error: "Search failed" }, { status: 500 })
  }
}
