/**
 * GET /api/dashboard/integration-health
 *   Live auth check + JWT expiry decode for each configured integration.
 *   Cached in-process for 5 minutes.
 *
 *   ?refresh=1 forces re-check (admin only).
 */

import { NextRequest, NextResponse } from 'next/server';
import { requireAuth, requirePermission } from '@/lib/auth-utils';
import {
  checkIntegrationHealth,
  clearIntegrationHealthCache,
  summarize,
} from '@/lib/services/integration-health';

export async function GET(request: NextRequest) {
  const refresh = request.nextUrl.searchParams.get('refresh') === '1';

  if (refresh) {
    const adminCheck = await requirePermission('admin', 'access');
    if (adminCheck.error) return adminCheck.error;
    clearIntegrationHealthCache();
  } else {
    const authCheck = await requireAuth();
    if (authCheck.error) return authCheck.error;
  }

  const items = await checkIntegrationHealth({ skipCache: refresh });
  return NextResponse.json({ items, summary: summarize(items) });
}
