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

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 { name, isAdmin, field, department, team, role } = await request.json()

    // Input validation
    if (!name || !field) {
      return NextResponse.json({ error: "Invalid name or field." }, { status: 400 })
    }

    // Validate field against managed types
    if (!(await hasManagedType("field", field))) {
      return NextResponse.json({ error: "Invalid field." }, { status: 400 })
    }

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

    if (normalizedDepartment && !(await hasManagedType("department", normalizedDepartment))) {
      return NextResponse.json({ error: "Invalid department." }, { status: 400 })
    }

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

    if (normalizedTeam && !(await hasManagedType("team", normalizedTeam))) {
      return NextResponse.json({ error: "Invalid team." }, { status: 400 })
    }

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

    if (fieldRows.length === 0 || (normalizedDepartment && departmentRows.length === 0) || (normalizedTeam && teamRows.length === 0)) {
      return NextResponse.json({ error: "Invalid field, department, or team." }, { status: 400 })
    }

    if (normalizedDepartment && departmentRows[0].parentId !== fieldRows[0].id) {
      return NextResponse.json({ error: "Department does not belong to field." }, { status: 400 })
    }

    if (normalizedTeam && normalizedDepartment && teamRows[0].parentId !== departmentRows[0].id) {
      return NextResponse.json({ error: "Team does not belong to department." }, { 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: "Invalid role." }, { status: 400 })
    }

    if (userRole === "field_admin") {
      if (!field || normalizedDepartment || normalizedTeam) {
        return NextResponse.json({ error: "Field admins must have a field only." }, { status: 400 })
      }
    } else if (userRole === "department_admin") {
      if (!field || !normalizedDepartment || normalizedTeam) {
        return NextResponse.json({ error: "Department admins must have field + department only." }, { status: 400 })
      }
    } else if (userRole === "team_admin" || userRole === "user") {
      if (!field || !normalizedDepartment || !normalizedTeam) {
        return NextResponse.json({ error: "Team/users require field, department, and team." }, { 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, normalizedDepartment, normalizedTeam],
    )

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