import { sendWhatsAppMessage } from '@/lib/whatsapp.js';
import { getDb, nowIso, newId } from '@/lib/db.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) {
  let body;
  try {
    body = await req.json();
  } catch {
    return new Response('Invalid JSON', { status: 400 });
  }
  try {
    await requireSession(req);
    const chatId = String(body?.chat_id || '').trim();
    const text = String(body?.text || '').trim();
    if (!chatId || !text) {
      return Response.json({ ok: false, error: 'chat_id and text are required' }, { status: 400 });
    }
    const result = await sendWhatsAppMessage(chatId, text);
    getDb().prepare(`
      INSERT INTO whatsapp_messages (id, direction, chat_id, sender, message_id, text, media_path, run_id, created_at)
      VALUES (?, 'outbound', ?, 'owner', ?, ?, NULL, NULL, ?)
    `).run(newId('wamsg'), chatId, result?.message_id || null, text, nowIso());
    appendAudit({
      type: 'whatsapp.outbound.manual',
      summary: 'Owner sent WhatsApp message from dashboard',
      status: 'sent',
      meta: { chat_id: chatId, message_id: result?.message_id || null },
    });
    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 });
  }
}
