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

export const runtime = "nodejs";

const SESSION_COOKIE_NAME = "gantt_session";
const SESSION_DAYS_REMEMBER = 30;

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);
    
    // Set cookie on response for Vercel compatibility
    const response = NextResponse.json({
      success: true,
      user,
      session: { expiresAt: session.expiresAt, rememberMe },
    });
    
    const baseCookieOptions = {
      httpOnly: true,
      sameSite: "lax" as const,
      secure: process.env.NODE_ENV === "production",
      path: "/",
    };
    
    if (rememberMe) {
      response.cookies.set(SESSION_COOKIE_NAME, session.token, {
        ...baseCookieOptions,
        maxAge: SESSION_DAYS_REMEMBER * 24 * 60 * 60,
      });
    } else {
      response.cookies.set(SESSION_COOKIE_NAME, session.token, baseCookieOptions);
    }

    return response;
  } catch {
    return NextResponse.json({ error: "Login failed" }, { status: 500 });
  }
}
