← back to Ken

src/app/api/alerts/route.js

49 lines

import { NextResponse } from 'next/server';
const { query } = require('../../../lib/db');
const { sendSlackAlert } = require('../../../lib/slack');

export const dynamic = 'force-dynamic';

export async function GET() {
  try {
    const res = await query('SELECT * FROM alerts_log ORDER BY ts DESC LIMIT 50');
    return NextResponse.json({ alerts: res.rows });
  } catch (err) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}

export async function POST(req) {
  const body = await req.json();

  if (body.action === 'test') {
    const result = await sendSlackAlert({
      type: 'SYSTEM TEST',
      severity: 'info',
      message: 'Bertha weather betting system test alert',
      details: { bankroll: '$50.00', mode: 'paper', status: 'operational' },
    });

    await query(`INSERT INTO alerts_log (alert_type, severity, message, slack_sent, details) VALUES ($1, $2, $3, $4, $5)`,
      ['test', 'info', 'Test alert sent', result.ok || false, { slack_result: result }]);

    return NextResponse.json({ sent: result.ok || false, result });
  }

  if (body.action === 'send') {
    const result = await sendSlackAlert({
      type: body.type || 'ALERT',
      severity: body.severity || 'info',
      message: body.message,
      details: body.details,
    });

    await query(`INSERT INTO alerts_log (alert_type, severity, message, slack_sent, details) VALUES ($1, $2, $3, $4, $5)`,
      [body.type || 'alert', body.severity || 'info', body.message, result.ok || false, body.details]);

    return NextResponse.json({ sent: result.ok || false });
  }

  return NextResponse.json({ error: 'Unknown action' }, { status: 400 });
}