import { NextResponse } from "next/server";
import { authenticateUser, createUserSession, setSessionCookie } from "@/lib/server/auth";

export const runtime = "nodejs";

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as {
      email?: string;
      password?: string;
      rememberMe?: boolean;
    };

    const email = (body.email || "").trim();
    const password = body.password || "";
    const rememberMe = Boolean(body.rememberMe);

    if (!email || !password) {
      return NextResponse.json({ error: "Email and password are required" }, { status: 400 });
    }

    const user = await authenticateUser({ email, password });
    if (!user) {
      return NextResponse.json({ error: "Invalid credentials" }, { status: 401 });
    }

    const session = await createUserSession(user.id, rememberMe);
    await setSessionCookie(session.token, rememberMe);

    return NextResponse.json({
      success: true,
      user,
      session: { expiresAt: session.expiresAt, rememberMe },
    });
  } catch {
    return NextResponse.json({ error: "Login failed" }, { status: 500 });
  }
}
