← back to Norma

app/api/cron/credential-health/route.ts

39 lines

import { NextRequest, NextResponse } from 'next/server';
import { verifyCronAuth } from '@/lib/cron-auth';
import { checkAllHealth, refreshExpiringTokens } from '@/lib/credentials';

/**
 * POST /api/cron/credential-health
 * Periodic health check + auto-refresh. Called every 30 min by PM2 cron.
 */
export async function POST(request: NextRequest) {
  const auth = verifyCronAuth(request);
  if (auth instanceof NextResponse) return auth;

  console.log('[cron:credential-health] Starting health check...');

  // Step 1: Refresh any expiring tokens
  const refreshResult = await refreshExpiringTokens();

  // Step 2: Check health of all services
  const health = await checkAllHealth();

  const summary = health.map((h) => `${h.platform}: ${h.status}`).join(', ');
  console.log(`[cron:credential-health] Done — ${summary}`);

  if (refreshResult.refreshed.length > 0) {
    console.log(`[cron:credential-health] Refreshed: ${refreshResult.refreshed.join(', ')}`);
  }
  if (refreshResult.failed.length > 0) {
    console.log(`[cron:credential-health] Failed refresh: ${refreshResult.failed.join(', ')}`);
  }

  return NextResponse.json({
    success: true,
    timestamp: new Date().toISOString(),
    refreshed: refreshResult.refreshed,
    failedRefresh: refreshResult.failed,
    health,
  });
}