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

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

    if (!adminId || !targetUserId || !status) {
      return NextResponse.json({ error: "נתונים חסרים" }, { status: 400 })
    }

    if (!["yes", "no", "no_alarm", "safe_after_exit"].includes(status)) {
      return NextResponse.json({ error: "סטטוס לא תקין" }, { status: 400 })
    }

    // Get admin data
    const adminData = (await safeQuery("SELECT role, field, department, team, name 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 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 status
    await safeQuery("UPDATE users SET in_shelter = ?, last_updated = NOW() WHERE national_id = ?", [
      status,
      targetUserId,
    ])

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

    const statusText =
          status === "yes"
            ? "במקלט/חדר מוגן"
            : status === "no"
              ? "לא במקלט"
              : status === "no_alarm"
                ? "אין אזעקה"
                : status === "safe_after_exit"
                  ? "בטוח אחרי יציאה מהמקלט"
                  : "לא ידוע"
        
        return NextResponse.json({
      success: true,
      message: `דווח עבור ${target.name}: ${statusText}`,
    })
  } catch (error) {
    console.error("Report on behalf error:", error)
    return NextResponse.json({ error: "שגיאה בדיווח" }, { status: 500 })
  }
}
