import { NextResponse } from "next/server";
import { getAuthenticatedUser, updateUserAccount } from "@/lib/server/auth";

export const runtime = "nodejs";

export async function PATCH(request: Request) {
  try {
    const sessionUser = await getAuthenticatedUser();
    if (!sessionUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = (await request.json()) as {
      name?: string;
      email?: string;
      avatarUrl?: string | null;
      currentPassword?: string;
      newPassword?: string;
    };

    const nextName = typeof body.name === "string" ? body.name : undefined;
    const nextEmail = typeof body.email === "string" ? body.email : undefined;
    const nextAvatarUrl = body.avatarUrl === null || typeof body.avatarUrl === "string" ? body.avatarUrl : undefined;
    const currentPassword = typeof body.currentPassword === "string" ? body.currentPassword : undefined;
    const newPassword = typeof body.newPassword === "string" ? body.newPassword : undefined;

    const user = await updateUserAccount({
      userId: sessionUser.id,
      name: nextName,
      email: nextEmail,
      avatarUrl: nextAvatarUrl,
      currentPassword,
      newPassword,
    });

    return NextResponse.json({ success: true, user });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Account update failed";
    if (message === "User not found") {
      return NextResponse.json({ error: message }, { status: 404 });
    }
    if (message === "Current password is incorrect") {
      return NextResponse.json({ error: message }, { status: 401 });
    }
    if (message.includes("exists")) {
      return NextResponse.json({ error: message }, { status: 409 });
    }
    if (
      message.includes("Current password is required")
      || message.includes("at least")
      || message.includes("Invalid email")
      || message.includes("Avatar")
    ) {
      return NextResponse.json({ error: message }, { status: 400 });
    }
    return NextResponse.json({ error: "Account update failed" }, { status: 500 });
  }
}
