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

    if (adminRole !== "department_admin" && adminRole !== "global_admin" || !adminField || !adminDepartment) {
      return NextResponse.json({ users: [], field: adminField, department: adminDepartment })
    }

    // Get department users with field and department context
    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 = ? AND department = ?
      ORDER BY team, name
    `,
      [adminField, adminDepartment],
    )) as any[]

    return NextResponse.json({
      users,
      field: adminField,
      department: adminDepartment,
    })
  } catch (error) {
    console.error("Department users error:", error)
    return NextResponse.json({ error: "שגיאה בטעינת משתמשי המסגרת" }, { status: 500 })
  }
}
