/**
 * Datto RMM Webhook Logs API
 * Browse captured webhook payloads for inspection.
 */

import { NextRequest, NextResponse } from 'next/server';
import { postgresClient } from '@/lib/services/postgres-client';

/**
 * GET /api/webhooks/datto-rmm/logs
 * Returns recent webhook logs, newest first.
 * Query params: limit (default 50), status (optional filter)
 */
export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const limit = Math.min(parseInt(searchParams.get('limit') || '50', 10), 500);
    const status = searchParams.get('status');

    let query = `SELECT * FROM datto_rmm_webhook_logs`;
    const params: any[] = [];

    if (status) {
      query += ` WHERE status = $1`;
      params.push(status);
    }

    query += ` ORDER BY received_at DESC LIMIT $${params.length + 1}`;
    params.push(limit);

    const result = await postgresClient.query(query, params);

    return NextResponse.json({
      success: true,
      count: result.rows.length,
      logs: result.rows,
    });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    console.error('[DATTO-RMM-WEBHOOK-LOGS] Error:', msg);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
