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: parsed.error.flatten() }, { status: 400 });
  const { nickname, password } = parsed.data;
  const user = await prisma.user.findUnique({ where: { nickname } });
  if (!user || !user.passwordHash || !verifyPassword(password, user.passwordHash)) {
    return NextResponse.json({ error: "아이디 또는 비밀번호가 올바르지 않습니다" }, { status: 401 });
  }
  return NextResponse.json({ user: { userId: user.userId, nickname: user.nickname } });
}


