#!/usr/bin/env node
/**
 * Simple webhook proxy for Uptime Kuma → Signal
 * Translates Uptime Kuma webhook payloads to signal-cli JSON-RPC
 * 
 * Run: node signal-webhook-proxy.js
 * Listens on port 8085
 */

const http = require('http');

const SIGNAL_RPC_URL = 'http://localhost:8080/api/v1/rpc';
const RECIPIENT = '+31634481877';
const PORT = 8085;

async function sendSignal(message) {
  const payload = {
    jsonrpc: '2.0',
    method: 'send',
    params: { recipient: RECIPIENT, message },
    id: Date.now()
  };

  const res = await fetch(SIGNAL_RPC_URL, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload)
  });
  return res.json();
}

const server = http.createServer(async (req, res) => {
  if (req.method !== 'POST') {
    res.writeHead(405);
    res.end('Method not allowed');
    return;
  }

  let body = '';
  req.on('data', chunk => body += chunk);
  req.on('end', async () => {
    try {
      const data = JSON.parse(body);
      
      // Extract message from Uptime Kuma payload
      // Uptime Kuma sends: { msg, monitor: { name }, heartbeat: { status, msg } }
      const message = data.msg || 
        `[${data.monitor?.name || 'Unknown'}] ${data.heartbeat?.status === 1 ? '🟢 UP' : '🔴 DOWN'}`;
      
      console.log(`[${new Date().toISOString()}] Forwarding to Signal: ${message.substring(0, 100)}...`);
      
      const result = await sendSignal(message);
      
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ ok: true, result }));
    } catch (err) {
      console.error('Error:', err.message);
      res.writeHead(500, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ ok: false, error: err.message }));
    }
  });
});

server.listen(PORT, '0.0.0.0', () => {
  console.log(`Signal webhook proxy listening on http://0.0.0.0:${PORT}`);
  console.log(`Configure Uptime Kuma webhook URL: http://james:${PORT}/`);
});
