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

const ALLOWED_PREFIXES = ["data:image/png;base64,", "data:image/jpeg;base64,", "data:image/gif;base64,"]
const MAX_AVATAR_BYTES = 2 * 1024 * 1024 // 2MB

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 })
    }

    const allowed = ALLOWED_PREFIXES.some((p) => avatar.startsWith(p))
    if (!allowed) {
      return NextResponse.json({ error: "Avatar must be a PNG, JPEG, or GIF data URL" }, { status: 400 })
    }

    // Approximate decoded size: base64 is ~4/3 of original
    const base64Data = avatar.split(",")[1] || ""
    const estimatedBytes = Math.round(base64Data.length * 0.75)
    if (estimatedBytes > MAX_AVATAR_BYTES) {
      return NextResponse.json({ error: "Avatar exceeds 2MB size limit" }, { 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 })
  }
}
