import { type NextRequest, NextResponse } from "next/server"
import { safeQuery } from "@/lib/database"
import { hashPassword } from "@/lib/auth"
import { type UserRole, DEPARTMENTS, TEAMS, FIELDS } from "@/types/user"

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

    // Input validation
    if (!name || !field || !department || !team) {
      return NextResponse.json({ error: "נתונים חסרים" }, { status: 400 })
    }

    // Validate department, team, and field
    if (!FIELDS.includes(field as any)) {
      return NextResponse.json({ error: "תחום לא תקין" }, { status: 400 })
    }

    if (!DEPARTMENTS.includes(department as any)) {
      return NextResponse.json({ error: "מסגרת לא תקינה" }, { status: 400 })
    }

    if (!TEAMS.includes(team as any)) {
      return NextResponse.json({ error: "צוות לא תקין" }, { status: 400 })
    }

    const validRoles: UserRole[] = ["user", "team_admin", "department_admin", "field_admin", "global_admin"]

    // Set role based on isAdmin flag or explicit role
    const userRole: UserRole = (role as UserRole) || (isAdmin ? "global_admin" : "user")

    if (!validRoles.includes(userRole)) {
      return NextResponse.json({ error: "תפקיד לא תקין" }, { status: 400 })
    }

    // Generate unique Login ID
    const { generateUniqueIsraeliID } = await import("@/lib/auth")
    const nationalId = await generateUniqueIsraeliID()

    // Hash default password "password123"
    const hashedPassword = await hashPassword("password123")

    await safeQuery(
      "INSERT INTO users (national_id, password, name, is_admin, role, must_change_password, field, department, team) VALUES (?, ?, ?, ?, ?, TRUE, ?, ?, ?)",
      [nationalId, hashedPassword, name, isAdmin, userRole, field, department, team],
    )

    return NextResponse.json({
      success: true,
      nationalId: nationalId,
      message: `משתמש ${name} נוסף בהצלחה עם מזהה: ${nationalId}`,
    })
  } catch (error) {
    console.error("Add user error:", error)
    return NextResponse.json({ error: "שגיאה בהוספת משתמש" }, { status: 500 })
  }
}
