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 and department
    const adminData = (await executeQuery(
      "SELECT field, department 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 { field: adminField, department: adminDepartment } = adminData[0]

    if (!adminField || !adminDepartment) {
      return NextResponse.json({ error: "למנהל לא הוגדרו תחום ומסגרת" }, { status: 400 })
    }

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

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