/**
 * POST /api/admin/rmm/settings/discover-loglift
 *
 * Force a re-scan of Datto RMM components, find the LogLift / event-log
 * collector component, and update rmm_settings. Returns the discovered
 * { uid, name } or 404 if nothing matches the discovery pattern.
 */

import { NextRequest, NextResponse } from 'next/server';
import { requirePermission } from '@/lib/auth-utils';
import { discoverLogliftComponent } from '@/lib/services/rmm/settings';

export async function POST(_request: NextRequest) {
  const { error } = await requirePermission('admin', 'access');
  if (error) return error;
  try {
    const result = await discoverLogliftComponent();
    if (!result.discovered) {
      return NextResponse.json(
        {
          error: 'No matching component found',
          message:
            'Datto RMM did not return any component whose name matches /loglift|eventlog/i. Register the LogLift collector component and retry.',
        },
        { status: 404 }
      );
    }
    return NextResponse.json({
      settings: result.settings,
      discovered: result.discovered,
    });
  } catch (err) {
    return NextResponse.json(
      {
        error: 'Discovery failed',
        message: err instanceof Error ? err.message : String(err),
      },
      { status: 500 }
    );
  }
}
