import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"

export async function POST(request: NextRequest) {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

    const { avatar } = await request.json()
    if (!avatar || typeof avatar !== "string") {
      return NextResponse.json({ error: "Invalid avatar data" }, { status: 400 })
    }

    await query(
      `UPDATE users SET avatar_url = $1 WHERE id = $2`,
      [avatar, user.id],
    )

    return NextResponse.json({ avatar })
  } catch (error) {
    console.error("Avatar upload error:", error)
    return NextResponse.json({ error: "Failed to update avatar" }, { status: 500 })
  }
}
