/**
 * RBAC API 代理 - 用户角色管理
 * POST /api/v3/rbac/users/:userId/roles - 为用户分配角色
 */

import { json, type LoaderFunctionArgs } from "@remix-run/node";
import { assignUserRole } from "~/services/rbac-mock-data.server";

// POST - 为用户分配角色
export async function action({ request, params }: LoaderFunctionArgs) {
  const userId = parseInt(params.userId || '0');
  const method = request.method;

  console.log('📡 [API Route]', method, '/api/v3/rbac/users/' + userId + '/roles');

  if (method === 'POST') {
    const body = await request.json();
    const roleIds = body.role_ids || [];

    console.log('📋 [API Route] 分配角色:', { userId, roleIds });

    // 使用共享Mock数据分配角色
    roleIds.forEach((roleId: number) => {
      assignUserRole(userId, roleId);
    });

    return json({
      code: 200,
      message: '角色分配成功',
      data: {
        user_id: userId,
        roles: roleIds.map((id: number) => ({ role_id: id }))
      }
    });
  }

  return json({ code: 405, message: 'Method Not Allowed' }, { status: 405 });
}
