import { NextResponse } from "next/server";

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

  const response = NextResponse.json({ user: body });

  const existingCookie = req.headers.get("cookie");
  let user = {};

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

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

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

  return response;
}
