import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { Prisma } from "@prisma/client";
import bcrypt from "bcryptjs";
import { apiHandler, ApiError } from "@/lib/api";
import { validateUsername, validatePassword } from "@/lib/validation";

export const POST = apiHandler(async (req) => {
  const { username, password, avatar } = await req.json();

  if (!username || !password) throw new ApiError("用户名和密码为必填项");

  const trimmedUsername = validateUsername(username);
  validatePassword(password);

  const passwordHash = await bcrypt.hash(password, 10);

  try {
    const user = await prisma.user.create({
      data: {
        username: trimmedUsername,
        passwordHash,
        avatar: avatar || "🐱",
      },
    });

    return NextResponse.json({
      id: user.id,
      username: user.username,
      avatar: user.avatar,
    });
  } catch (e) {
    if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002") {
      throw new ApiError("用户名已被注册", 409);
    }
    throw e;
  }
});
