/**
 * RBAC API 代理 - 获取角色列表
 * GET /api/v3/rbac/roles
 */

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

// GET - 获取角色列表
export async function loader({ request }: LoaderFunctionArgs) {
  console.log('📡 [API Route] GET /api/v3/rbac/roles 被调用');

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

  console.log('📋 [API Route] 查询参数:', { page, pageSize, roleKey, roleName });

  // 过滤数据
  let filteredRoles = [...mockRoles];

  if (roleKey) {
    filteredRoles = filteredRoles.filter(r => r.role_key.includes(roleKey));
  }

  if (roleName) {
    filteredRoles = filteredRoles.filter(r => r.role_name.includes(roleName));
  }

  // 添加用户数统计
  const rolesWithCount = filteredRoles.map(role => ({
    ...role,
    user_count: mockUserRoles.filter(ur => ur.role_id === role.id).length,
    permission_count: 0 // 暂时写死
  }));

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

  // 返回标准格式
  const response = {
    code: 200,
    message: 'success',
    data: {
      total,
      page,
      page_size: pageSize,
      items
    }
  };

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

  return json(response, {
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization'
    }
  });
}

// POST - 创建角色
export async function action({ request }: LoaderFunctionArgs) {
  const method = request.method;

  if (method === 'POST') {
    console.log('📡 [API Route] POST /api/v3/rbac/roles 被调用');

    const body = await request.json();
    console.log('📋 [API Route] 请求体:', body);

    // 使用共享Mock数据
    const newRole = addRole({
      role_key: body.role_key,
      role_name: body.role_name,
      description: body.description || '',
      data_scope: body.data_scope || 'SELF',
      priority: body.priority || 10,
      is_system: false
    });

    console.log('✅ [API Route] 角色创建成功:', newRole);

    return json({
      code: 200,
      message: '角色创建成功',
      data: newRole
    });
  }

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