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

const API = process.env.NEXT_PUBLIC_API_URL ?? 'http://127.0.0.1:3000';

/** FIX-14: logout hits the backoffice endpoint and clears backoffice_session. */
export async function POST() {
  try {
    const { cookies } = await import('next/headers');
    const token = (await cookies()).get('backoffice_session')?.value;
    await fetch(`${API}/backoffice/auth/logout`, {
      method: 'POST',
      headers: token ? { Cookie: `backoffice_session=${token}` } : {},
    });
  } catch {
    /* ignore */
  }
  const res = NextResponse.json({ ok: true }, { status: 200 });
  res.cookies.set('backoffice_session', '', { path: '/', maxAge: 0 });
  return res;
}