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

const hasManagedType = async (type: "field" | "department" | "team", name: string) => {
  const rows = (await safeQuery("SELECT 1 FROM managed_types WHERE type = ? AND name = ? LIMIT 1", [
    type,
    name,
  ])) as any[]
  if (rows.length > 0) {
    return true
  }

  const legacyRows = (await safeQuery(`SELECT 1 FROM users WHERE ${type} = ? LIMIT 1`, [name])) as any[]
  return legacyRows.length > 0
}

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

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

    const adminRows = (await safeQuery("SELECT role, field, department, team FROM users WHERE national_id = ?", [
      adminId,
    ])) as any[]
    if (adminRows.length === 0) {
      return NextResponse.json({ error: "הרשאת מנהל לא נמצאה" }, { status: 404 })
    }

    const admin = adminRows[0]

    const userRows = (await safeQuery("SELECT national_id, role, field, department, team FROM users WHERE national_id = ?", [
      targetUserId,
    ])) as any[]
    if (userRows.length === 0) {
      return NextResponse.json({ error: "משתמש לא נמצא." }, { status: 404 })
    }
    const targetUser = userRows[0]

    const normalizedDepartment = typeof department === "string" && department.trim() ? department.trim() : null
    const normalizedTeam = typeof team === "string" && team.trim() ? team.trim() : null

    if (targetUser.role !== "field_admin" && !normalizedDepartment) {
      return NextResponse.json({ error: "Missing required fields." }, { status: 400 })
    }

    if ((targetUser.role === "team_admin" || targetUser.role === "user") && !normalizedTeam) {
      return NextResponse.json({ error: "Missing required fields." }, { status: 400 })
    }

    const effectiveDepartment = targetUser.role === "field_admin" ? null : normalizedDepartment
    const effectiveTeam = targetUser.role === "field_admin" ? null : normalizedTeam


    const [fieldOk, departmentOk, teamOk] = await Promise.all([
      hasManagedType("field", field),
      effectiveDepartment ? hasManagedType("department", effectiveDepartment) : Promise.resolve(true),
      effectiveTeam ? hasManagedType("team", effectiveTeam) : Promise.resolve(true),
    ])

    if (!fieldOk || !departmentOk || !teamOk) {
      return NextResponse.json({ error: "תחום, מסגרת או צוות שגויים." }, { status: 400 })
    }

    const fieldRows = (await safeQuery("SELECT id FROM managed_types WHERE type = 'field' AND name = ?", [
      field,
    ])) as Array<{ id: number }>
    const departmentRows = effectiveDepartment
      ? ((await safeQuery(
          "SELECT id, parent_id AS parentId FROM managed_types WHERE type = 'department' AND name = ?",
          [effectiveDepartment],
        )) as Array<{ id: number; parentId: number | null }>)
      : []
    const teamRows = effectiveTeam
      ? ((await safeQuery("SELECT id, parent_id AS parentId FROM managed_types WHERE type = 'team' AND name = ?", [
          effectiveTeam,
        ])) as Array<{ id: number; parentId: number | null }>)
      : []

    if (fieldRows.length === 0 || (effectiveDepartment && departmentRows.length === 0) || (effectiveTeam && teamRows.length === 0)) {
      return NextResponse.json({ error: "תחום, מסגרת או צוות שגויים." }, { status: 400 })
    }

    if (effectiveDepartment && departmentRows[0].parentId !== fieldRows[0].id) {
      return NextResponse.json({ error: "מסגרת לא משוייכת לתחום הנבחר." }, { status: 400 })
    }

    if (effectiveTeam && teamRows[0].parentId !== departmentRows[0].id) {
      return NextResponse.json({ error: "צוות לא משוייך למסגרת הנבחרת." }, { status: 400 })
    }

    if (admin.role === "field_admin") {
      if (targetUser.field !== admin.field) {
        return NextResponse.json({ error: "המשתמש הנבחר לא משוייך לתחום שלך." }, { status: 403 })
      }
      if (field !== admin.field) {
        return NextResponse.json({ error: "מנהלי תחומים רשאים לנהל אך ורק את התחום שלהם." }, { status: 403 })
      }
    } else if (admin.role === "department_admin") {
      if (targetUser.department !== admin.department) {
        return NextResponse.json({ error: "המשתמש הנבחר לא משוייך למסגרת שלך." }, { status: 403 })
      }
      if (department !== admin.department) {
        return NextResponse.json({ error: "מנהלי מסגרות רשאים לנהל אך ורק את המסגרת שלהם." }, { status: 403 })
      }
      if (admin.field && field !== admin.field) {
        return NextResponse.json({ error: "מנהלי מסגרות רשאים לנהל אך ורק באותו התחום." }, { status: 403 })
      }
    } else if (admin.role === "team_admin") {
      if (targetUser.team !== admin.team) {
        return NextResponse.json({ error: "המשתמש הנבחר לא משוייך לצוות שלך." }, { status: 403 })
      }
      if (effectiveTeam !== admin.team) {
        return NextResponse.json({ error: "מנהלי צוותים רשאים לנהל אך ורק את הצוות שלהם." }, { status: 403 })
      }
      if (admin.department && department !== admin.department) {
        return NextResponse.json({ error: "מנהלי צוותים רשאים לנהל אך ורק באותה המסגרת." }, { status: 403 })
      }
      if (admin.field && field !== admin.field) {
        return NextResponse.json({ error: "מנהלי צוותים ראשאים לנהל אך ורק באותו התחום." }, { status: 403 })
      }
    } else if (admin.role !== "global_admin") {
      return NextResponse.json({ error: "הרשאות לא מספיקות." }, { status: 403 })
    }

    await safeQuery("UPDATE users SET field = ?, department = ?, team = ? WHERE national_id = ?", [
      field,
      effectiveDepartment,
      effectiveTeam,
      targetUserId,
    ])

    return NextResponse.json({ success: true, message: "משתמש עודכן בהצלחה." })
  } catch (error) {
    console.error("Update user scope error:", error)
    return NextResponse.json({ error: "עדכון משתמש נכשל." }, { status: 500 })
  }
}
