import { NextResponse } from "next/server";
import { getToken, TOKEN_COOKIE } from "@/lib/session";

const API_URL = process.env.NEXT_PUBLIC_API_URL;

/**
 * Invoked by a plain <form method="post"> (see AuthStatus) — no client JS
 * needed. Revokes the token on Laravel (best effort) and always clears the
 * local cookie, then redirects home.
 */
export async function POST(request: Request) {
  const token = await getToken();

  if (token) {
    await fetch(`${API_URL}/auth/logout`, {
      method: "POST",
      headers: { Accept: "application/json", Authorization: `Bearer ${token}` },
    }).catch(() => null);
  }

  const response = NextResponse.redirect(new URL("/", request.url));
  response.cookies.delete(TOKEN_COOKIE);

  return response;
}
