import { logoutWhatsApp } from '@/lib/whatsapp.js';
import { appendAudit } from '@/lib/runtime.js';
import { requireSession } from '@/lib/auth.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function POST(req) {
  try {
    await requireSession(req);
    const result = await logoutWhatsApp();
    appendAudit({
      type: 'whatsapp.disconnect',
      summary: 'Owner disconnected WhatsApp from dashboard',
      status: 'done',
      meta: {},
    });
    return Response.json({ ok: true, ...result });
  } catch (err) {
    if (err && typeof err === 'object' && err.status) {
      return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
    }
    return Response.json({ ok: false, error: err.message }, { status: err.status || 502 });
  }
}
