import { NextApiResponse } from 'next';
import { AuthenticatedRequest } from '@/lib/middleware/authMiddleware';
import { requireAdmin } from '@/lib/middleware/adminMiddleware';
import { UserService } from '@/backend/services/userService';

export default async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
  if (req.method !== 'POST') {
    return res.status(405).json({ success: false, error: 'Method not allowed' });
  }

  const isAdmin = await requireAdmin(req, res);
  if (!isAdmin) return;

  const { id } = req.query;
  const { role } = req.body || {};

  if (typeof id !== 'string' || typeof role !== 'string') {
    return res.status(400).json({ success: false, error: 'Invalid input' });
  }

  try {
    const updated = await UserService.updateUserRole(id, role as any);
    return res.status(200).json({ success: true, data: updated });
  } catch (error) {
    console.error('Error updating role:', error);
    return res.status(500).json({ success: false, error: 'Failed to update role' });
  }
}
