import { vi } from 'vitest';

/**
 * 创建模拟的认证上下文
 */
export function createMockAuthContext(overrides: Partial<any> = {}) {
  const baseContext = {
    req: {
      header: (name: string) => {
        const headers: Record<string, string> = {
          'authorization': 'Bearer test-token-123',
          'content-type': 'application/json',
          'user-agent': 'vitest/integration-test',
          'x-request-id': `test_${Math.random().toString(36).substr(2, 9)}`
        };
        return headers[name.toLowerCase()] || null;
      }
    },
    set: vi.fn(),
    json: vi.fn().mockImplementation((data, status = 200) => ({
      status,
      body: data
    })),
    status: vi.fn().mockReturnThis(),
    body: vi.fn().mockReturnThis(),
    env: {
      NODE_ENV: 'test',
      DATABASE_URL: process.env.TEST_DATABASE_URL || 'mysql://root:test@localhost:3306/test_d8dai'
    },
    var: {},
    get: vi.fn()
  };

  return { ...baseContext, ...overrides };
}

/**
 * 创建模拟的JWT用户信息
 */
export function createMockJwtPayload(overrides: Partial<any> = {}) {
  return {
    sub: '1',
    username: 'testuser',
    email: 'test@example.com',
    roles: ['user'],
    iat: Math.floor(Date.now() / 1000),
    exp: Math.floor(Date.now() / 1000) + 3600, // 1小时后过期
    ...overrides
  };
}

/**
 * 创建模拟的认证中间件
 */
export function createMockAuthMiddleware() {
  return vi.fn().mockImplementation(async (c: any, next: () => Promise<void>) => {
    // 模拟认证用户信息
    c.set('user', {
      id: 1,
      username: 'testuser',
      email: 'test@example.com',
      roles: ['user']
    });
    await next();
  });
}

/**
 * 创建模拟的权限中间件
 */
export function createMockPermissionMiddleware(requiredRoles: string[] = []) {
  return vi.fn().mockImplementation(async (c: any, next: () => Promise<void>) => {
    const user = c.get('user');

    if (!user) {
      return c.json({ error: 'Unauthorized' }, 401);
    }

    if (requiredRoles.length > 0) {
      const hasRole = requiredRoles.some(role => user.roles?.includes(role));
      if (!hasRole) {
        return c.json({ error: 'Forbidden' }, 403);
      }
    }

    await next();
  });
}