/**
 * Avatar Upload API
 * POST - Upload user profile picture
 */

import { NextRequest, NextResponse } from "next/server";
import { writeFile, mkdir } from "fs/promises";
import { join } from "path";
import { createId } from "@paralleldrive/cuid2";
import { auth } from "@/lib/auth";
import { logger } from "@/lib/logger";
import { convexMutation } from "@/lib/convex-client";
import { getAuthenticatedConvexUser } from "@/lib/convex-auth-state";

const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp", "image/gif"];
const MAX_SIZE = 5 * 1024 * 1024;
const UPLOAD_DIR = join(process.cwd(), "public", "uploads", "avatars");

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

    const formData = await request.formData();
    const file = formData.get("file") as File | null;

    if (!file) {
      return NextResponse.json({ error: "No file provided" }, { status: 400 });
    }

    if (!ALLOWED_TYPES.includes(file.type)) {
      return NextResponse.json(
        { error: "Invalid file type. Use JPEG, PNG, WebP, or GIF." },
        { status: 400 },
      );
    }

    if (file.size > MAX_SIZE) {
      return NextResponse.json(
        { error: "File too large. Maximum 5MB." },
        { status: 400 },
      );
    }

    const ALLOWED_EXTENSIONS = new Set(["jpg", "jpeg", "png", "webp", "gif"]);
    const rawExt = (file.name.split(".").pop() || "").toLowerCase();
    const ext = ALLOWED_EXTENSIONS.has(rawExt) ? rawExt : "jpg";
    const filename = `${createId()}.${ext}`;

    await mkdir(UPLOAD_DIR, { recursive: true });

    const bytes = await file.arrayBuffer();
    const filePath = join(UPLOAD_DIR, filename);
    await writeFile(filePath, Buffer.from(bytes));

    const avatarUrl = `/uploads/avatars/${filename}`;

    await convexMutation("auth/mutations:updateUserNoAuth", {
      userId: user.id,
      avatar: avatarUrl,
    });

    logger.info("Avatar uploaded", { userId: user.id, avatarUrl });

    return NextResponse.json({
      success: true,
      avatarUrl,
    });
  } catch (error) {
    logger.error(
      "Avatar upload failed",
      error instanceof Error ? error : new Error(String(error)),
    );
    return NextResponse.json(
      { error: "Failed to upload avatar" },
      { status: 500 },
    );
  }
}
