/**
 * RBAC API 代理 - 单个角色操作
 * GET /api/v3/rbac/roles/:roleId - 获取角色详情
 * PUT /api/v3/rbac/roles/:roleId - 更新角色
 * DELETE /api/v3/rbac/roles/:roleId - 删除角色
 */

import { json, type LoaderFunctionArgs } from "@remix-run/node";
import { mockRoles, updateRole as updateMockRole, deleteRole as deleteMockRole } from "~/services/rbac-mock-data.server";

// GET - 获取角色详情
export async function loader({ params }: LoaderFunctionArgs) {
  const roleId = parseInt(params.roleId || '0');
  console.log('📡 [API Route] GET /api/v3/rbac/roles/' + roleId);

  const role = mockRoles.find(r => r.id === roleId);

  if (!role) {
    return json({
      detail: '角色不存在'
    }, { status: 404 });
  }

  return json({
    code: 200,
    message: 'success',
    data: role
  });
}

// PUT/DELETE
export async function action({ request, params }: LoaderFunctionArgs) {
  const roleId = parseInt(params.roleId || '0');
  const method = request.method;

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

  const role = mockRoles.find(r => r.id === roleId);

  if (!role) {
    return json({
      detail: '角色不存在'
    }, { status: 404 });
  }

  if (method === 'PUT') {
    // 更新角色
    const body = await request.json();
    console.log('📋 [API Route] 更新数据:', body);

    // 系统角色保护
    if (role.is_system && body.role_key) {
      return json({
        detail: '系统角色的role_key不可修改'
      }, { status: 400 });
    }

    // 使用共享Mock数据更新
    updateMockRole(roleId, body);

    return json({
      code: 200,
      message: '角色更新成功',
      data: role
    });
  }

  if (method === 'DELETE') {
    // 删除角色
    if (role.is_system) {
      return json({
        detail: '系统角色不能删除'
      }, { status: 400 });
    }

    // 使用共享Mock数据删除
    deleteMockRole(roleId);

    return json({
      code: 200,
      message: '角色删除成功'
    });
  }

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