import { NextResponse } from "next/server";

export async function POST(request: Request) {
  const body = await request.json();

  const response = NextResponse.json({});

  // Read existing cookie from request
  const cookieHeader = request.headers.get("cookie");
  let user = {};

  if (cookieHeader) {
    const match = cookieHeader
      .split("; ")
      .find(c => c.startsWith("session="));

    if (match) {
      user = JSON.parse(decodeURIComponent(match?.split("=")[1]));
    }
  }

  const updatedUser = { ...user, ...body.user };
  console.log("LOGIN", updatedUser);
  response.cookies.set("session", JSON.stringify(updatedUser), {
    httpOnly: true,
    path: "/",
    maxAge: 30 * 24 * 60 * 60,
    sameSite: "lax",
  });

  return response;
}
