// ── Users: Avatar Upload ────────────────────────────────────────────────────
// POST /api/users/avatar  — Update the current user's avatar (base64 data URL)
//
// Auth: authenticated
// Accepts PNG, JPEG, GIF data URIs up to 2MB decoded size.

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

// ── Constants ────────────────────────────────────────────────────────────────

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

// ── POST ─────────────────────────────────────────────────────────────────────

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

    // Validate image format by checking the data URL prefix
    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 encodes ~4 bytes as 3 bytes of data
    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 })
    }

    // Store the full data URL in the avatar_url column
    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 })
  }
}
