import { NextRequest, NextResponse } from 'next/server';
import { logError } from '@/lib/logger';
import { requireAdmin } from '@/lib/auth-server';
import { listUsers, getUserCounts, registerUser } from '@/lib/platform-client';
import { getRequestProductId } from '@/lib/product-config';

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 url = new URL(req.url);
    const limit = parseInt(url.searchParams.get('limit') ?? '100', 10);
    const offset = parseInt(url.searchParams.get('offset') ?? '0', 10);

    const [usersResult, countsResult] = await Promise.all([
      listUsers(token, limit, offset),
      getUserCounts(token),
    ]);

    return NextResponse.json({
      users: usersResult.users,
      total: countsResult.total,
      byPlan: countsResult.byPlan,
    });
  } catch (error) {
    logError('List users error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

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

    const body = await req.json();
    const { email, name, password, role = 'user' } = body;
    if (!email || !name || !password) {
      return NextResponse.json(
        { error: 'email, name, and password are required' },
        { status: 400 }
      );
    }

    const result = await registerUser({
      email,
      password,
      displayName: name,
      role,
      productId: getRequestProductId(req),
    });

    return NextResponse.json(result.user, { status: 201 });
  } catch (error) {
    logError('Create user error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
