import type { ActionFunctionArgs } from "@remix-run/node";
import { getSession, commitSession, destroySession } from "~/lib/session.server";

export async function action({ request }: ActionFunctionArgs) {
  const session = await getSession(request);

  if (request.method === "DELETE") {
    return new Response(JSON.stringify({ ok: true }), {
      headers: {
        "Content-Type": "application/json",
        "Set-Cookie": await destroySession(session),
      },
    });
  }

  const body = await request.json();
  const token = body?.token;

  if (!token || typeof token !== "string") {
    return new Response(JSON.stringify({ error: "Token required" }), {
      status: 400,
      headers: { "Content-Type": "application/json" },
    });
  }

  session.set("auth_token", token);

  return new Response(JSON.stringify({ ok: true }), {
    headers: {
      "Content-Type": "application/json",
      "Set-Cookie": await commitSession(session),
    },
  });
}
