/**
 * RMM Components API — list available Datto RMM automation components for quick jobs.
 */

import { NextResponse } from 'next/server';
import { DattoRMMClient } from '@/lib/services/datto-rmm-client';

let _client: DattoRMMClient | null = null;
function getClient(): DattoRMMClient {
  if (!_client) {
    _client = new DattoRMMClient({
      apiUrl: process.env.DATTO_RMM_API_URL || 'https://concord-api.centrastage.net/api/v2',
      apiKey: process.env.DATTO_RMM_API_KEY || '',
      apiSecret: process.env.DATTO_RMM_API_SECRET || '',
    });
  }
  return _client;
}

export async function GET() {
  try {
    const client = getClient();
    const components = await client.getComponents();

    return NextResponse.json({
      data: components,
      total: components.length,
    });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
