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

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

    if (!adminId || !targetUserId || typeof lockStatus !== "boolean") {
      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]

    // Get target user data
    const targetData = (await safeQuery(
      "SELECT field, department, team, name, lock_status FROM users WHERE national_id = ?",
      [targetUserId],
    )) as any[]

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

    const target = targetData[0]

    // Check if admin can manage this user based on hierarchy
    let canManage = false

    if (admin.role === "global_admin") {
      canManage = true
    } else if (admin.role === "field_admin" && admin.field === target.field) {
      canManage = true
    } else if (admin.role === "department_admin" && admin.department === target.department) {
      canManage = true
    } else if (admin.role === "team_admin" && admin.team === target.team) {
      canManage = true
    }

    if (!canManage) {
      return NextResponse.json({ error: "אין הרשאה לנעול/לבטל נעילה של משתמש זה" }, { status: 403 })
    }

    // Update user lock status
    await safeQuery("UPDATE users SET lock_status = ? WHERE national_id = ?", [lockStatus, targetUserId])

    // Log the action
    const actionType = lockStatus ? "lock_user" : "unlock_user"
    await safeQuery("INSERT INTO admin_actions (admin_id, action_type, target_user_id) VALUES (?, ?, ?)", [
      adminId,
      actionType,
      targetUserId,
    ])

    const statusText = lockStatus ? "נעול" : "לא נעול"

    return NextResponse.json({
      success: true,
      message: `סטטוס נעילה של ${target.name} שונה ל: ${statusText}`,
      lockStatus,
    })
  } catch (error) {
    console.error("Toggle user lock error:", error)
    return NextResponse.json({ error: "שגיאה בשינוי סטטוס נעילה" }, { status: 500 })
  }
}
