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, 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({ users: [], field: adminField, department: adminDepartment, team: adminTeam })
    }

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

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