import { listInboundAllowlist, addAllowlistEntry, removeAllowlistEntry } from '@/lib/whatsapp-router.js';
import { appendAudit } from '@/lib/runtime.js';
import { requireSession } from '@/lib/auth.js';

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

function normalizeChatId(value) {
  const raw = String(value || '').trim();
  if (!raw) return '';
  if (raw.includes('@')) return raw;
  const digits = raw.replace(/[^0-9]/g, '');
  if (!digits) return '';
  return `${digits}@s.whatsapp.net`;
}

function catchAuth(err) {
  if (err && typeof err === 'object' && err.status) {
    return Response.json({ error: err.error || 'unauthorized' }, { status: err.status });
  }
  return null;
}

export async function GET(req) {
  try {
    await requireSession(req);
    return Response.json({ ok: true, allowlist: listInboundAllowlist() });
  } catch (err) {
    return catchAuth(err) ?? Response.json({ ok: false, error: err.message }, { status: 500 });
  }
}

export async function POST(req) {
  let body;
  try {
    body = await req.json();
  } catch {
    return new Response('Invalid JSON', { status: 400 });
  }
  try {
    await requireSession(req);
    const chatId = normalizeChatId(body?.chat_id);
    if (!chatId) {
      return Response.json({ ok: false, error: 'chat_id is required (digits or full JID)' }, { status: 400 });
    }
    const entry = addAllowlistEntry({
      chat_id: chatId,
      kind: body?.kind || (chatId.endsWith('@g.us') ? 'group' : 'dm'),
      label: body?.label || null,
    });
    appendAudit({
      type: 'whatsapp.allowlist.add',
      summary: `Added WhatsApp chat to allowlist`,
      status: 'added',
      meta: { chat_id: chatId, label: body?.label || null },
    });
    return Response.json({ ok: true, entry }, { status: 201 });
  } catch (err) {
    return catchAuth(err) ?? Response.json({ ok: false, error: err.message }, { status: 500 });
  }
}

export async function DELETE(req) {
  try {
    await requireSession(req);
    const { searchParams } = new URL(req.url);
    const chatId = normalizeChatId(searchParams.get('chat_id'));
    if (!chatId) {
      return Response.json({ ok: false, error: 'chat_id query param is required' }, { status: 400 });
    }
    const removed = removeAllowlistEntry(chatId);
    appendAudit({
      type: 'whatsapp.allowlist.remove',
      summary: 'Removed WhatsApp chat from allowlist',
      status: 'removed',
      meta: { chat_id: chatId, removed },
    });
    return Response.json({ ok: true, removed });
  } catch (err) {
    return catchAuth(err) ?? Response.json({ ok: false, error: err.message }, { status: 500 });
  }
}
