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

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

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

    const updated = await prisma.user.update({
      where: { id: userId },
      data: { role },
      select: { id: true, email: true, role: true },
    });

    return NextResponse.json({ ok: true, user: updated });
  } catch (error) {
    if (String(error).includes('Unauthorized')) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
    console.error('Update role error', error);
    return NextResponse.json({ error: 'Failed to update role' }, { status: 500 });
  }
}
export const dynamic = 'force-dynamic';
