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

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

    if (!adminId) {
      return NextResponse.json({ error: "מזהה מנהל חסר" }, { status: 400 })
    }

    // Get admin's field
    const adminData = (await executeQuery("SELECT field 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 adminField = adminData[0].field

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

    // Get field users
    const users = (await executeQuery(
      `
      SELECT 
        national_id,
        name,
        role,
        in_shelter,
        last_updated,
        is_admin,
        must_change_password,
        field,
        department,
        team,
        lock_status
      FROM users
      WHERE field = ?
      ORDER BY department, team, name
    `,
      [adminField],
    )) as any[]

    return NextResponse.json({
      users,
      field: adminField,
    })
  } catch (error) {
    console.error("Field users error:", error)
    return NextResponse.json({ error: "שגיאה בטעינת משתמשי התחום" }, { status: 500 })
  }
}
