import { NextResponse } from "next/server";
import { createSessionToken, SESSION_COOKIE } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { verifyPassword } from "@/lib/password";
import { getClientIp, rateLimitFailedLogin } from "@/lib/rate-limit";
import {
  clearLegacyRootSessionCookie,
  sessionCookieBase,
} from "@/lib/session-cookie";

export async function POST(request: Request) {
  const ip = getClientIp(request);

  let body: { email?: string; password?: string };
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Corps invalide" }, { status: 400 });
  }

  const email = String(body.email ?? "")
    .trim()
    .toLowerCase();
  const password = String(body.password ?? "");

  if (!email || !password) {
    return NextResponse.json(
      { error: "Email et mot de passe requis" },
      { status: 400 }
    );
  }

  const user = await prisma.user.findUnique({ where: { email } });
  const valid =
    !!user && (await verifyPassword(password, user.passwordHash));
  if (!valid) {
    const limited = await rateLimitFailedLogin(ip);
    if (!limited.ok) {
      return NextResponse.json(
        {
          error: "Trop de tentatives. Réessayez plus tard.",
          retryAfterSec: limited.retryAfterSec,
        },
        {
          status: 429,
          headers: { "Retry-After": String(limited.retryAfterSec) },
        }
      );
    }
    return NextResponse.json({ error: "Identifiants invalides" }, { status: 401 });
  }

  const token = await createSessionToken(user.id);
  const res = NextResponse.json({ ok: true });
  res.cookies.set(SESSION_COOKIE, token, {
    ...sessionCookieBase(),
    maxAge: 60 * 60 * 24 * 7,
  });
  clearLegacyRootSessionCookie(res);
  return res;
}
