import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import { requireAdmin } from '@/lib/auth-server';
import { countActiveTokens } from '@/lib/repositories/tokens';
import * as billingClient from '@/lib/billing-client';
import * as platformClient from '@/lib/platform-client';

export async function GET(req: NextRequest) {
  try {
    const admin = await requireAdmin(req);
    if (!admin) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const token = req.headers.get('authorization')?.replace('Bearer ', '') ?? '';
    const [countsResult, activeTokens, usageRes, auditStatsRes] = await Promise.all([
      platformClient.getUserCounts(token),
      countActiveTokens(),
      billingClient.getUsageSummary(30),
      platformClient.getAuditStats(90),
    ]);
    const auditTotal = Object.values(auditStatsRes.stats).reduce((s, n) => s + n, 0);
    const failedLogins = auditStatsRes.stats['login_failed'] ?? 0;
    return NextResponse.json({
      users: { total: countsResult.total, byPlan: countsResult.byPlan },
      tokens: { active: activeTokens },
      usage: {
        totalWords: usageRes.totalWords ?? 0,
        totalDictations: usageRes.totalDictations ?? 0,
        totalCost: usageRes.totalCost ?? 0,
      },
      audit: { total: auditTotal, failedLogins },
    });
  } catch (error) {
    logError('Dashboard stats error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
