/**
 * User impersonation (read-only) — returns full user profile + recent usage
 * so admins can see exactly what a user sees without modifying anything.
 *
 * GET /api/users/:id/view
 */

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

export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const caller = await requireAdmin(req);
    if (!caller) return NextResponse.json({ error: 'Forbidden' }, { status: 403 });

    const token = req.headers.get('authorization')?.replace('Bearer ', '') ?? '';
    const { id } = await params;
    const profile = await platformClient.getUser(token, id);

    // Fetch user-specific usage (last 30 days)
    let recentUsage: { records: unknown[] } = { records: [] };
    try {
      recentUsage = await billingClient.listUsage({ userId: id, days: 30 });
    } catch {
      // Non-fatal — usage data may not be available
    }
    return NextResponse.json({
      profile,
      usage: recentUsage,
      viewedBy: { id: caller.id, name: caller.name, role: caller.role },
      viewedAt: new Date().toISOString(),
    });
  } catch (error) {
    logError('User impersonation view error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
