import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { Pool } from 'pg';
import { getDattoRMMClient } from '@/lib/services/datto-rmm-factory';

const pool = new Pool({
  host: process.env.POSTGRES_HOST,
  port: parseInt(process.env.POSTGRES_PORT || '5432'),
  database: process.env.POSTGRES_DB,
  user: process.env.POSTGRES_USER,
  password: process.env.POSTGRES_PASSWORD,
});

export async function GET(request: NextRequest) {
  const authError = validateOpenClawKey(request);
  if (authError) return authError;

  const params = request.nextUrl.searchParams;
  const live = params.get('live') === 'true';
  const siteUid = params.get('siteUid');
  const deviceUid = params.get('deviceUid');
  const limit = Math.min(1000, Math.max(1, parseInt(params.get('limit') || '200', 10)));

  try {
    if (live) {
      const client = getDattoRMMClient();
      let alerts = await client.getAllOpenAlerts();

      if (siteUid) alerts = alerts.filter((a: any) => a.siteUid === siteUid);
      if (deviceUid) alerts = alerts.filter((a: any) => a.deviceUid === deviceUid);

      return NextResponse.json({
        data: alerts.slice(0, limit),
        total: alerts.length,
        source: 'live',
      });
    }

    const conditions: string[] = ['resolved = false'];
    const values: unknown[] = [];

    if (siteUid) {
      values.push(siteUid);
      conditions.push(`site_uid = $${values.length}`);
    }
    if (deviceUid) {
      values.push(deviceUid);
      conditions.push(`device_uid = $${values.length}`);
    }

    values.push(limit);
    const result = await pool.query(
      `SELECT
        alert_uid, alert_category, alert_type, alert_message_en,
        device_uid, device_hostname, device_ip, device_os, device_description,
        site_uid, site_name,
        resolved, muted, ticket_number,
        timestamp, platform, triggered,
        alert_context, alert_monitor_info,
        last_user, ping_target,
        synced_at, updated_at
       FROM datto_rmm_alerts
       WHERE ${conditions.join(' AND ')}
       ORDER BY timestamp DESC
       LIMIT $${values.length}`,
      values
    );

    return NextResponse.json({
      data: result.rows,
      total: result.rowCount,
      source: 'db',
    });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
