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

// export async function POST() {
//   const cookieStore = cookies();
//   const allCookies = cookieStore.getAll();

//   console.log("Clearing the following cookies:");

//   // 获取当前请求的 host（服务器端）
//   const hostHeader = headers().get("host");
//   const currentHost = hostHeader || "localhost"; // 如果没有 host 信息，使用 "localhost"

//   // Loop through all cookies and clear them
//   allCookies.forEach(({ name }) => {
//     console.log(`............Clearing cookie: ${name}`);
//     try {
//       cookieStore.set({
//         name,
//         value: "",
//         path: "/",
//         maxAge: 0,
//         httpOnly: true,
//         secure: true,
//         sameSite: "lax",
//         domain: currentHost,  // 使用服务器端获取的 host
//       });
//     } catch (error) {
//       console.error(`Error clearing cookie ${name}:`, error);
//     }
//   });

//   // Return success response using NextResponse
//   return NextResponse.json({ message: "Cookies cleared successfully" }, { status: 200 });
// }


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

export async function POST() {
  const cookieStore = cookies();
  const allCookies = cookieStore.getAll();

  console.log("🔍 Clearing the following cookies:");
  allCookies.forEach(({ name }) => console.log(`- ${name}`));

  const response = NextResponse.json(
    { message: "Cookies cleared successfully" },
    { status: 200 }
  );

  // Clear each cookie by setting an expired value
  allCookies.forEach(({ name }) => {
    try {
      response.cookies.set({
        name,
        value: "",
        path: "/",
        maxAge: 0,
        httpOnly: true,
        secure: process.env.NODE_ENV === "production", // ← 自动判断环境
        sameSite: "lax",
        // No domain — will auto match current domain
      });
    } catch (error) {
      console.error(`❌ Error clearing cookie ${name}:`, error);
    }
  });

  return response;
}
