import { NextResponse } from "next/server";
import { destroySession, getSession, writeAuditLog } from "@/lib/auth";

export async function POST(req: Request) {
  try {
    // Capture session before destroying it (for audit log)
    const session = await getSession();

    if (session) {
      await writeAuditLog({
        clinicId: session.id,
        action:   "logout",
        actor:    session.email,
        resource: session.sessionId,
        request:  req,
      });
    }

    await destroySession();

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("[Logout]", error);
    // Always clear the cookie even on error
    await destroySession().catch(() => {});
    return NextResponse.json({ success: true });
  }
}
