import { NextResponse } from 'next/server';
import { prisma } from '../../../../../lib/prisma';
import { requireAuth } from '../../../../../lib/jwt';
import { Role, UserStatus } from '@prisma/client';

export async function POST(req: Request) {
  try {
    const auth = await requireAuth(req);
    const canReject = auth.role === Role.ADMIN || auth.role === Role.USER_MODERATOR;
    if (!canReject) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const body = await req.json();
    const userId = String(body.userId ?? '');
    const reason = body.reason ? String(body.reason).slice(0, 500) : null;

    if (!userId) {
      return NextResponse.json({ error: 'userId is required' }, { status: 400 });
    }

    const updated = await prisma.user.update({
      where: { id: userId },
      data: {
        status: UserStatus.REJECTED,
        rejectedAt: new Date(),
        rejectedReason: reason,
        approvedAt: null,
      },
      select: { id: true, role: true, status: true, rejectedAt: true, rejectedReason: true },
    });

    return NextResponse.json({ ok: true, user: updated });
  } catch (error) {
    if (String(error).includes('Unauthorized')) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    console.error('Admin reject user error', error);
    return NextResponse.json({ error: 'Reject failed' }, { status: 500 });
  }
}
export const dynamic = 'force-dynamic';
