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 isAdmin = auth.role === Role.ADMIN;
    const canApprove = isAdmin || auth.role === Role.USER_MODERATOR;
    if (!canApprove) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const body = await req.json();
    const userId = String(body.userId ?? '');
    const makeAdmin = Boolean(body.makeAdmin);
    const newRole = body.newRole as Role | undefined;
    if (!userId) {
      return NextResponse.json({ error: 'userId is required' }, { status: 400 });
    }

    if (!isAdmin && (makeAdmin || newRole === Role.ADMIN || newRole === Role.USER_MODERATOR || newRole === Role.LISTING_MODERATOR)) {
      return NextResponse.json({ error: 'Only admins can change roles' }, { status: 403 });
    }

    const roleUpdate = isAdmin && newRole ? { role: newRole } : makeAdmin && isAdmin ? { role: Role.ADMIN } : undefined;

    const updated = await prisma.user.update({
      where: { id: userId },
      data: {
        status: UserStatus.ACTIVE,
        approvedAt: new Date(),
        rejectedAt: null,
        rejectedReason: null,
        removedAt: null,
        removedById: null,
        removedReason: null,
        ...(roleUpdate ?? {}),
      },
      select: { id: true, role: true, status: true, approvedAt: 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 approve user error', error);
    return NextResponse.json({ error: 'Approval failed' }, { status: 500 });
  }
}
export const dynamic = 'force-dynamic';
