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

export const runtime = "nodejs";

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

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

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

    const user = await registerUser({ name, email, password });
    const session = await createUserSession(user.id, rememberMe);
    await setSessionCookie(session.token, rememberMe);

    return NextResponse.json({
      success: true,
      user,
      session: { expiresAt: session.expiresAt, rememberMe },
    });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Registration failed";
    const status = message.includes("exists") ? 409 : 400;
    return NextResponse.json({ error: message }, { status });
  }
}
