import { describe, it, expect } from '@jest/globals';
const request = require('supertest');
import { app } from '../../test-app';

describe('RBAC权限测试', () => {
  const roles = [
    { name: 'ADMIN', token: 'admin-token', shouldHaveAccess: true },
    { name: 'MANAGER', token: 'manager-token', shouldHaveAccess: true },
    { name: 'OPERATOR', token: 'operator-token', shouldHaveAccess: false },
    { name: 'FINANCE', token: 'finance-token', shouldHaveAccess: false },
    { name: 'SOURCING', token: 'sourcing-token', shouldHaveAccess: false },
    { name: 'LOGISTICS', token: 'logistics-token', shouldHaveAccess: false },
    { name: 'ANALYST', token: 'analyst-token', shouldHaveAccess: false }
  ];

  it('应该根据角色权限控制对管理接口的访问', async () => {
    for (const role of roles) {
      const response = await request(app)
        .get('/api/v1/admin/users')
        .set('x-tenant-id', 'test-tenant')
        .set('x-trace-id', `rbac-trace-${role.name}`)
        .set('Authorization', `Bearer ${role.token}`);

      if (role.shouldHaveAccess) {
        expect(response.status).toBe(200);
        expect(response.body.success).toBe(true);
        console.log(`${role.name} 角色成功访问管理接口`);
      } else {
        expect(response.status).toBe(403);
        expect(response.body.success).toBe(false);
        expect(response.body.message).toBe('权限不足');
        console.log(`${role.name} 角色被正确拒绝访问管理接口`);
      }
    }
  });

  it('应该允许所有角色访问公共接口', async () => {
    for (const role of roles) {
      const response = await request(app)
        .get('/api/v1/products')
        .set('x-tenant-id', 'test-tenant')
        .set('x-trace-id', `rbac-public-${role.name}`)
        .set('Authorization', `Bearer ${role.token}`)
        .expect(200);

      expect(response.body.success).toBe(true);
      expect(response.body.data).toBeInstanceOf(Array);
    }

    console.log('所有角色都成功访问公共接口');
  });

  it('应该拒绝未授权的访问', async () => {
    const response = await request(app)
      .get('/api/v1/admin/users')
      .set('x-tenant-id', 'test-tenant')
      .set('x-trace-id', 'rbac-unauthorized')
      .expect(401);

    expect(response.body.success).toBe(false);
    expect(response.body.message).toBe('未授权');
    console.log('未授权访问被正确拒绝');
  });

  it('应该根据用户层级限制数据访问', async () => {
    // 模拟不同层级的用户
    const users = [
      { userId: 'admin-1', role: 'ADMIN', shouldSeeAll: true },
      { userId: 'manager-1', role: 'MANAGER', shouldSeeAll: false }
    ];

    for (const user of users) {
      const response = await request(app)
        .get('/api/v1/users')
        .set('x-tenant-id', 'test-tenant')
        .set('x-trace-id', `rbac-hierarchy-${user.role}`)
        .set('Authorization', `Bearer ${user.role.toLowerCase()}-token`)
        .expect(200);

      expect(response.body.success).toBe(true);
      expect(response.body.data).toBeInstanceOf(Array);
      
      // 这里可以根据实际的层级过滤逻辑添加更具体的断言
      console.log(`${user.role} 角色的数据访问测试通过`);
    }
  });
});
