import { NextResponse } from "next/server";
import { cookies } from "next/headers";

export async function GET() {
  if (!process.env.SECNEX_API_HOST || !process.env.SECNEX_API_KEY) {
    return NextResponse.json({ success: false, message: "SecNex API host or key is not set" });
  }
  const cookieStore = await cookies();
  const token = cookieStore.get("token");
  if (!token) {
    console.log("No token found");
    return NextResponse.json({ success: false, message: "No token found" });
  }
  console.log("Token found");
  const response = await fetch(`${process.env.SECNEX_API_HOST}/logout`, {
    method: "POST",
    body: JSON.stringify({ token: token.value }),
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${process.env.SECNEX_API_KEY}`,
    },
  });
  if (!response.ok) {
    const data = await response.json();
    cookieStore.delete("token");
    console.log("Token deleted");
    return NextResponse.json({ success: false, message: data.body.message });
  }
  const data = await response.json();
  cookieStore.delete("token");
  console.log("Token deleted");
  console.log("Logout successful");
  return NextResponse.json({ success: true, message: data.body.message });
}