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

export async function POST(request: NextRequest) {
  try {
    const { adminId, category } = await request.json()

    if (!adminId || !category) {
      return NextResponse.json({ error: "נתונים חסרים" }, { status: 400 })
    }

    // Get admin's field, department, and team
    const adminData = (await executeQuery(
      "SELECT role, field, department, team FROM users WHERE national_id = ? AND role IS NOT NULL AND role != 'user'",
      [adminId],
    )) as any[]

    if (adminData.length === 0) {
      return NextResponse.json({ error: "מנהל לא נמצא" }, { status: 404 })
    }

    const { role: adminRole, field: adminField, department: adminDepartment, team: adminTeam } = adminData[0]

    if (adminRole !== "team_admin" && adminRole !== "global_admin" || !adminField || !adminDepartment || !adminTeam) {
      return NextResponse.json([])
    }

    let query = ""
    const params: any[] = [adminField, adminDepartment, adminTeam]

    switch (category) {
      case "no_report":
        query =
          "SELECT national_id, name FROM users WHERE field = ? AND department = ? AND team = ? AND in_shelter IS NULL ORDER BY name"
        break
      case "in_shelter":
        query =
          "SELECT national_id, name FROM users WHERE field = ? AND department = ? AND team = ? AND in_shelter = 'yes' ORDER BY name"
        break
      case "not_in_shelter":
        query =
          "SELECT national_id, name FROM users WHERE field = ? AND department = ? AND team = ? AND in_shelter = 'no' ORDER BY name"
        break
      case "no_alarm":
        query =
          "SELECT national_id, name FROM users WHERE field = ? AND department = ? AND team = ? AND in_shelter = 'no_alarm' ORDER BY name"
        break
      case "safe_after_exit":
        query =
          "SELECT national_id, name FROM users WHERE field = ? AND department = ? AND team = ? AND 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 team users by category error:", error)
    return NextResponse.json({ error: "שגיאה בטעינת משתמשי הצוות" }, { status: 500 })
  }
}
