import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import { getCurrentUserFromRequest } from '@/lib/auth-server';
import * as actiontrailClient from '@/lib/actiontrail-client';

export async function GET(req: NextRequest) {
  try {
    const caller = await getCurrentUserFromRequest(req);
    if (!caller) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    const url = new URL(req.url);
    const section = url.searchParams.get('section') ?? 'actions';
    const userId = url.searchParams.get('userId') ?? caller.id;
    const limit = parseInt(url.searchParams.get('limit') ?? '50', 10);

    switch (section) {
      case 'actions': {
        const result = await actiontrailClient.getActions(userId, limit);
        return NextResponse.json(result);
      }
      case 'agents': {
        const result = await actiontrailClient.getAgents(userId);
        return NextResponse.json(result);
      }
      case 'alerts': {
        const result = await actiontrailClient.getAlerts(userId, limit);
        return NextResponse.json(result);
      }
      case 'approvals': {
        const result = await actiontrailClient.getPendingApprovals(userId);
        return NextResponse.json(result);
      }
      case 'summary': {
        const result = await actiontrailClient.getInsightsSummary(userId);
        return NextResponse.json(result);
      }
      case 'bootstrap': {
        const result = await actiontrailClient.getBootstrap();
        return NextResponse.json(result);
      }
      default:
        return NextResponse.json({ error: `Unknown section: ${section}` }, { status: 400 });
    }
  } catch (error) {
    logError('ActionTrail proxy error', error);
    return NextResponse.json({ error: 'ActionTrail service unavailable' }, { status: 502 });
  }
}
