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

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

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

    // Get admin data
    const adminData = (await safeQuery("SELECT role, field, department, team FROM users WHERE national_id = ?", [
      adminId,
    ])) as any[]

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

    const admin = adminData[0]
    let query = ""
    let params: any[] = []

    // Build query based on admin role
    if (admin.role === "global_admin") {
      query = `
        SELECT 
          national_id, 
          name, 
          role, 
          field, 
          department, 
          team, 
          in_shelter, 
          last_updated,
          lock_status,
          is_admin,
          must_change_password
        FROM users 
        ORDER BY field, department, team, name
      `
    } else if (admin.role === "field_admin") {
      query = `
        SELECT 
          national_id, 
          name, 
          role, 
          field, 
          department, 
          team, 
          in_shelter, 
          last_updated,
          lock_status,
          is_admin,
          must_change_password
        FROM users 
        WHERE field = ?
        ORDER BY department, team, name
      `
      params = [admin.field]
    } else if (admin.role === "department_admin") {
      query = `
        SELECT 
          national_id, 
          name, 
          role, 
          field, 
          department, 
          team, 
          in_shelter, 
          last_updated,
          lock_status,
          is_admin,
          must_change_password
        FROM users 
        WHERE department = ?
        ORDER BY team, name
      `
      params = [admin.department]
    } else if (admin.role === "team_admin") {
      // Team admins can only manage their own team members
      query = `
        SELECT 
          national_id, 
          name, 
          role, 
          field, 
          department, 
          team, 
          in_shelter, 
          last_updated,
          lock_status,
          is_admin,
          must_change_password
        FROM users 
        WHERE team = ? AND role = 'user'
        ORDER BY name
      `
      params = [admin.team]
    } else {
      return NextResponse.json({ error: "אין הרשאות ניהול" }, { status: 403 })
    }

    const users = (await safeQuery(query, params)) as any[]

    console.log("Manageable users query result:", users) // Debug log

    return NextResponse.json({
      users,
      adminRole: admin.role,
      scope: {
        field: admin.field,
        department: admin.department,
        team: admin.team,
      },
    })
  } catch (error) {
    console.error("Get manageable users error:", error)
    return NextResponse.json({ error: "שגיאה בטעינת משתמשים" }, { status: 500 })
  }
}
