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,
  { params }: { params: Promise<{ uid: string }> }
) {
  const authError = validateOpenClawKey(request);
  if (authError) return authError;

  const { uid } = await params;
  const live = request.nextUrl.searchParams.get('live') === 'true';

  try {
    if (live) {
      const client = getDattoRMMClient();
      const device = await client.getDeviceById(uid);
      if (!device) {
        return NextResponse.json({ error: 'Device not found' }, { status: 404 });
      }
      return NextResponse.json({ data: device, source: 'live' });
    }

    const result = await pool.query(
      `SELECT
        id, uid, site_id, site_uid, site_name, hostname, description,
        device_type_category, device_type, operating_system, domain,
        int_ip_address, ext_ip_address, last_logged_in_user,
        last_seen, last_reboot, last_audit_date, creation_date,
        online, suspended, deleted, reboot_required, a64_bit,
        cag_version, display_version,
        antivirus_product, antivirus_status,
        patch_status, patches_approved_pending, patches_not_approved, patches_installed,
        software_status, portal_url, web_remote_url, warranty_date,
        snmp_enabled, device_class, network_probe,
        udf, synced_at, updated_at
       FROM datto_rmm_devices
       WHERE uid = $1`,
      [uid]
    );

    if (result.rowCount === 0) {
      return NextResponse.json({ error: 'Device not found' }, { status: 404 });
    }

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