/**
 * RBAC API 代理 - 角色用户管理
 * GET /api/v3/rbac/roles/:roleId/users - 获取角色的用户列表
 */

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

// GET - 获取角色的用户列表
export async function loader({ params, request }: LoaderFunctionArgs) {
  const roleId = parseInt(params.roleId || '0');
  console.log('📡 [API Route] GET /api/v3/rbac/roles/' + roleId + '/users');

  // 解析查询参数
  const url = new URL(request.url);
  const page = parseInt(url.searchParams.get('page') || '1');
  const pageSize = parseInt(url.searchParams.get('page_size') || '20');
  const area = url.searchParams.get('area');
  const username = url.searchParams.get('username');

  // 使用共享Mock数据获取角色用户
  let users = getRoleUsers(roleId);

  // 过滤
  if (area) {
    users = users.filter(u => u.area.includes(area));
  }

  if (username) {
    users = users.filter(u =>
      u.username.includes(username) || u.nick_name.includes(username)
    );
  }

  // 添加assigned_at时间戳
  const usersWithTime = users.map(user => {
    const userRole = mockUserRoles.find(
      ur => ur.user_id === (user.user_id || user.id) && ur.role_id === roleId
    );
    return {
      ...user,
      user_id: user.user_id || user.id,
      assigned_at: userRole?.assigned_at || new Date().toISOString()
    };
  });

  // 分页
  const total = usersWithTime.length;
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  const items = usersWithTime.slice(start, end);

  console.log('✅ [API Route] 返回用户数据:', { roleId, total, itemsCount: items.length });

  return json({
    code: 200,
    message: 'success',
    data: {
      total,
      page,
      page_size: pageSize,
      items
    }
  });
}
