// ── Event Users ─────────────────────────────────────────────────────────────
// GET /api/event-users  — List all active users available for event assignment
//
// Auth: authenticated
// Returns users with their roles, excluding the current user (cannot assign
// events to yourself as a participant). Used by the calendar UI for dropdowns.

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

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

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

    const result = await query(
      `SELECT u.id, u.first_name, u.last_name, u.email,
              ur.role_id, r.name AS role_name, r.display_name AS role_display
       FROM users u
       LEFT JOIN user_roles ur ON ur.user_id = u.id
       LEFT JOIN roles r ON r.id = ur.role_id
       WHERE u.deleted_at IS NULL AND u.id != $1
       ORDER BY u.first_name ASC`,
      [user.id],
    )

    const users = result.rows.map((r: any) => ({
      id: r.id,
      name: `${r.first_name} ${r.last_name}`,
      email: r.email,
      role: r.role_display || r.role_name || "",
    }))

    return NextResponse.json({ users })
  } catch (error) {
    console.error("Event users error:", error)
    return NextResponse.json({ error: "Failed to load users" }, { status: 500 })
  }
}
