// ==================== 认证与用户信息 Mock 数据 ====================

// 模拟用户数据
const mockUsers = [
    {
        id: 'current_user',
        username: 'zhangsan',
        realName: '张三',
        email: 'zhangsan@jianke.com',
        phone: '13800138000',
        department: '技术研发部',
        position: '高级开发工程师',
        avatar: '',
        roles: ['user', 'developer'],
    },
    {
        id: 'user_001',
        username: 'lisi',
        realName: '李四',
        email: 'lisi@jianke.com',
        phone: '13800138001',
        department: '人力资源部',
        position: '人力资源经理',
        avatar: '',
        roles: ['user'],
    },
    {
        id: 'user_002',
        username: 'wangwu',
        realName: '王五',
        email: 'wangwu@jianke.com',
        phone: '13800138002',
        department: '项目管理部',
        position: '项目总监',
        avatar: '',
        roles: ['user', 'manager'],
    },
];

// 模拟验证码（实际场景应该发送到手机/邮箱）
let verificationCodes: Record<string, { code: string; expiresAt: number }> = {};

/**
 * 生成随机验证码
 */
function generateVerificationCode(): string {
    return String(Math.floor(Math.random() * 9000) + 1000);
}

/**
 * 模拟登录请求
 * POST /auth/login
 */
export const mockLogin = async (request: { data?: { username?: string; password?: string; code?: string } }) => {
    const { username, password, code } = request.data || {};

    console.log('[Mock] 登录请求', { username, code });

    // 验证验证码（可选，简化流程）
    if (code && verificationCodes[username || 'default']) {
        const savedCode = verificationCodes[username || 'default'];
        if (savedCode.code !== code) {
            return {
                code: 400,
                message: '验证码错误',
                data: null,
            };
        }
        // 验证码使用后失效
        delete verificationCodes[username || 'default'];
    }

    // 简化验证：只要用户名密码不为空即可
    if (!username || !password) {
        return {
            code: 400,
            message: '用户名或密码不能为空',
            data: null,
        };
    }

    // 查找用户
    const user = mockUsers.find(u => u.username === username);

    // 返回模拟 Token
    const mockToken = `mock_token_${username}_${Date.now()}`;
    const mockRefreshToken = `mock_refresh_token_${username}_${Date.now()}`;

    return {
        code: 200,
        message: '登录成功',
        data: {
            token: mockToken,
            refreshToken: mockRefreshToken,
            expiresAt: Date.now() + 7 * 24 * 60 * 60 * 1000, // 7 天有效期
            user: user || mockUsers[0], // 返回用户信息
        },
    };
};

/**
 * 获取验证码
 * GET /auth/code
 */
export const mockGetVerificationCode = async (request: { params?: { phone?: string; email?: string } }) => {
    const { phone, email } = request.params || {};

    console.log('[Mock] 获取验证码', { phone, email });

    // 生成验证码
    const code = generateVerificationCode();
    const key = phone || email || 'default';

    // 存储验证码（5 分钟有效期）
    verificationCodes[key] = {
        code,
        expiresAt: Date.now() + 5 * 60 * 1000,
    };

    console.log('[Mock] 验证码（仅供调试）:', code);

    return {
        code: 200,
        message: '验证码已发送',
        data: {
            // 开发环境返回验证码，生产环境应隐藏
            debugCode: code,
            expiresInSeconds: 300,
        },
    };
};

/**
 * 获取当前用户信息
 * GET /system/user/getInfo
 */
export const mockGetUserInfo = async (request: { headers?: { Authorization?: string } }) => {
    const token = request.headers?.Authorization || '';

    console.log('[Mock] 获取用户信息', { token });

    // 从 Token 中提取用户名（简化处理）
    const username = token.replace('mock_token_', '').split('_')[0] || 'zhangsan';
    const user = mockUsers.find(u => u.username === username) || mockUsers[0];

    return {
        code: 200,
        message: 'success',
        data: {
            ...user,
            permissions: ['app:create', 'app:edit', 'app:delete', 'knowledge:manage'],
        },
    };
};

/**
 * 退出登录
 * POST /auth/logout
 */
export const mockLogout = async () => {
    console.log('[Mock] 退出登录');

    return {
        code: 200,
        message: '退出成功',
        data: null,
    };
};

/**
 * 刷新 Token
 * POST /auth/refresh
 */
export const mockRefreshToken = async (request: { data?: { refreshToken?: string } }) => {
    const { refreshToken } = request.data || {};

    console.log('[Mock] 刷新 Token', { refreshToken });

    const mockToken = `mock_token_refreshed_${Date.now()}`;

    return {
        code: 200,
        message: 'success',
        data: {
            token: mockToken,
            refreshToken: refreshToken || `mock_refresh_token_${Date.now()}`,
            expiresAt: Date.now() + 7 * 24 * 60 * 60 * 1000,
        },
    };
};

// ==================== 导出所有 Mock 处理函数 ====================

export const authMockHandlers = {
    'POST /auth/login': mockLogin,
    'GET /auth/code': mockGetVerificationCode,
    'GET /system/user/getInfo': mockGetUserInfo,
    'POST /auth/logout': mockLogout,
    'POST /auth/refresh': mockRefreshToken,
};
