import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";
import { loginSchema } from "@/lib/validation/auth";
import { verifyPassword } from "@/lib/password";
import { getClientKey, isRateLimited } from "@/lib/ratelimit";

export async function POST(req: Request) {
  const key = getClientKey(req, "login");
  if (isRateLimited(key, 5, 60_000)) {
    return NextResponse.json({ error: "Too Many Requests" }, { status: 429 });
  }
  const body = await req.json();
  const parsed = loginSchema.safeParse(body);
  if (!parsed.success)
    return NextResponse.json(
      { error: "아이디 또는 비밀번호가 일치하지 않습니다" },
      { status: 401 }
    );
  const { id, password } = parsed.data;
  // DB에서는 로그인 아이디를 nickname 컬럼으로 보관
  const user = await prisma.user.findUnique({ where: { nickname: id } });
  if (!user || !user.passwordHash || !verifyPassword(password, user.passwordHash)) {
    return NextResponse.json(
      { error: "아이디 또는 비밀번호가 일치하지 않습니다" },
      { status: 401 }
    );
  }
  return NextResponse.json({ user: { userId: user.userId, nickname: user.nickname } });
}


