import { type NextRequest, NextResponse } from "next/server";
import { executeQuery } from "@/lib/database";

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const category = searchParams.get("category");

    let query = "";
    // No params needed for these queries, as there are no WHERE conditions
    // that use parameters other than the in_shelter status itself.
    let params: any[] = []; 

    switch (category) {
      case "no_report":
        // Added 'department', 'team', 'field' to SELECT clause
        query = "SELECT national_id, name, department, team, field FROM users WHERE in_shelter IS NULL ORDER BY name";
        break;
      case "in_shelter":
        // Added 'department', 'team', 'field' to SELECT clause
        query = "SELECT national_id, name, department, team, field FROM users WHERE in_shelter = 'yes' ORDER BY name";
        break;
      case "not_in_shelter":
        // Added 'department', 'team', 'field' to SELECT clause
        query = "SELECT national_id, name, department, team, field FROM users WHERE in_shelter = 'no' ORDER BY name";
        break;
      case "no_alarm":
        // Added 'department', 'team', 'field' to SELECT clause
        query = "SELECT national_id, name, department, team, field FROM users WHERE in_shelter = 'no_alarm' ORDER BY name";
        break;
      case "safe_after_exit":
        // Added 'department', 'team', 'field' to SELECT clause
        query = "SELECT national_id, name, department, team, field FROM users WHERE in_shelter = 'safe_after_exit' ORDER BY name";
        break;
      default:
        return NextResponse.json({ error: "קטגוריה לא תקינה" }, { status: 400 });
    }

    const users = (await executeQuery(query, params)) as any[];
    return NextResponse.json(users);
  } catch (error) {
    console.error("Get users by category error:", error);
    return NextResponse.json({ error: "שגיאה בטעינת משתמשים" }, { status: 500 });
  }
}