import { type NextRequest, NextResponse } from "next/server"
import { safeQuery } from "@/lib/database"
import { type UserRole, ROLE_HIERARCHY, ROLE_NAMES } from "@/types/user"

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

    if (!adminId || !targetUserId || !newRole) {
      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]
    const adminLevel = ROLE_HIERARCHY[admin.role as UserRole] || 0

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

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

    const target = targetData[0]
    const newRoleLevel = ROLE_HIERARCHY[newRole as UserRole] || 0

    // Check if admin has permission to change this role
    if (adminLevel <= newRoleLevel) {
      return NextResponse.json({ error: "אין הרשאה לתת תפקיד זה" }, { status: 403 })
    }

    // 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 role
    await safeQuery("UPDATE users SET role = ? WHERE national_id = ?", [newRole, targetUserId])

    // Log the action
    await safeQuery(
      'INSERT INTO admin_actions (admin_id, action_type, target_user_id, target_role) VALUES (?, "role_change", ?, ?)',
      [adminId, targetUserId, newRole],
    )

    return NextResponse.json({
      success: true,
      message: `תפקיד ${target.name} שונה ל${ROLE_NAMES[newRole as UserRole]}`,
    })
  } catch (error) {
    console.error("Change role error:", error)
    return NextResponse.json({ error: "שגיאה בשינוי תפקיד" }, { status: 500 })
  }
}
