// ── Users: Phone Lookup ──────────────────────────────────────────────────────
// GET /api/users/lookup?phone=  — Look up a user by phone number
//
// Auth: admin/super_admin only
// Returns found: true + user data or found: false if no match.

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

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

export async function GET(request: NextRequest) {
  const sessionUser = await getSessionUser()
  if (!sessionUser) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
  }

  if (sessionUser.role !== "super_admin" && sessionUser.role !== "admin") {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 })
  }

  const phone = request.nextUrl.searchParams.get("phone")
  if (!phone) {
    return NextResponse.json({ error: "Phone parameter required" }, { status: 400 })
  }

  try {
    const result = await query(
      `SELECT id, username, first_name, last_name, phone, avatar_url
       FROM users
       WHERE phone = $1 AND deleted_at IS NULL
       LIMIT 1`,
      [phone],
    )

    if (result.rows.length === 0) {
      return NextResponse.json({ found: false })
    }

    const user = result.rows[0]
    return NextResponse.json({
      found: true,
      user: {
        id: user.id,
        username: user.username,
        firstName: user.first_name,
        lastName: user.last_name,
        phone: user.phone,
        avatar: user.avatar_url,
      },
    })
  } catch {
    return NextResponse.json({ error: "Lookup failed" }, { status: 500 })
  }
}
