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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ uid: string }> }
) {
  const authError = validateOpenClawKey(request);
  if (authError) return authError;

  const { uid } = await params;

  try {
    const client = getDattoRMMClient();
    const audit = await client.getDeviceAudit(uid);

    if (!audit) {
      return NextResponse.json(
        { error: 'Audit data not found for this device' },
        { status: 404 }
      );
    }

    return NextResponse.json({ data: audit, source: 'live' });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
