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

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

    const token = req.headers.get('authorization')?.replace('Bearer ', '') ?? '';
    const { id } = await params;
    const user = await platformClient.getUser(token, id);
    return NextResponse.json(user);
  } catch (error) {
    logError('Get user error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

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

    const token = req.headers.get('authorization')?.replace('Bearer ', '') ?? '';
    const { id } = await params;
    const body = await req.json();
    const updated = await platformClient.updateUser(token, id, body);
    return NextResponse.json(updated);
  } catch (error) {
    logError('Update user error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}

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

    const token = req.headers.get('authorization')?.replace('Bearer ', '') ?? '';
    const { id } = await params;
    const result = await platformClient.deleteUser(token, id);
    return NextResponse.json(result);
  } catch (error) {
    logError('Delete user error', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
