import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import bcrypt from "bcryptjs";
import { apiHandler, ApiError } from "@/lib/api";

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

  if (!username || !password) throw new ApiError("请输入用户名和密码");

  const user = await prisma.user.findUnique({ where: { username: username.trim() } });
  if (!user) throw new ApiError("用户名或密码错误", 401);

  const valid = await bcrypt.compare(password, user.passwordHash);
  if (!valid) throw new ApiError("用户名或密码错误", 401);

  return NextResponse.json({
    id: user.id,
    username: user.username,
    avatar: user.avatar,
  });
});
