/**
 * 认证相关的 Mock 处理器
 */
import { http, HttpResponse } from 'msw';
import {
  mockUsers,
  loginSuccessData,
  loginErrorResponses,
  userInfoData,
  logoutData,
} from '../data/auth.js';
import {
  generateToken,
  delay,
  validateRequired,
  validatePasswordLength,
  createSuccessResponse,
  createErrorResponse,
  extractToken,
  isValidToken,
} from '../utils.js';

// 存储当前登录的用户信息（模拟服务器端 session）
let currentUser = {
  error: 0,
  msg: '个人信息',
  data: {
    status_text: '正常',
    is_super: true,
    id: 1,
    role_id: 1,
    account: 'admin',
    nickname: 'admin',
    mobile: null,
    avatar: '/static/img/admin/avatar.png',
    email: null,
    login_fail: 0,
    login_time: 1751867554,
    login_ip: '125.121.73.44',
    status: 'normal',
    create_time: '2025-02-14 16:31:20',
    update_time: '2025-07-07 13:52:34',
    role: {
      status_text: '正常',
      id: 1,
      parent_id: 0,
      name: '超级管理组',
      code: 'root',
      description: null,
      rules: ['*'],
      status: 'normal',
      create_time: '2025-02-14 16:31:14',
      update_time: '2025-02-14 16:31:14',
    },
    oauth_info: null,
  },
};

export const authHandlers = [
  // 登录接口
  http.post('https://shop.trust-will.com/admin/index/login', async ({ request }) => {
    // 模拟网络延迟
    await delay(300);

    try {
      const body = await request.json();
      const { account, password } = body;

      // 验证必填字段
      const requiredError = validateRequired(body, ['account', 'password']);
      if (requiredError) {
        return HttpResponse.json(requiredError);
      }

      // 验证密码长度
      const passwordError = validatePasswordLength(password);
      if (passwordError) {
        return HttpResponse.json(passwordError);
      }

      // 查找用户
      const user = mockUsers.find((u) => u.account === account);
      if (!user) {
        return HttpResponse.json(loginErrorResponses.accountNotFound);
      }

      // 验证密码
      if (user.password !== password) {
        return HttpResponse.json(loginErrorResponses.passwordError);
      }

      // 检查账号状态
      if (user.status !== 1) {
        return HttpResponse.json(loginErrorResponses.accountDisabled);
      }

      // 生成 Token
      const token = generateToken();

      // 保存当前用户信息
      currentUser = { ...user, token };

      // 返回成功响应
      return HttpResponse.json(
        createSuccessResponse(
          {
            token,
            userInfo: {
              id: user.id,
              account: user.account,
              nickname: user.nickname,
              avatar: user.avatar,
              role: user.role,
            },
          },
          '登录成功',
        ),
      );
    } catch (error) {
      return HttpResponse.json(createErrorResponse('请求数据格式错误'));
    }
  }),

  // 获取用户信息接口
  http.get('https://shop.trust-will.com/admin/index/profile', async () => {
    await delay(200);

    // 直接返回写死的用户信息
    return HttpResponse.json(currentUser);
  }),

  // 登出接口
  http.post('https://shop.trust-will.com/admin/index/logout', async ({ request }) => {
    await delay(200);

    const token = extractToken(request);

    // 验证 Token
    if (!token || !isValidToken(token)) {
      return HttpResponse.json(createErrorResponse('未登录', 401));
    }

    // 清除当前用户信息
    currentUser = null;

    return HttpResponse.json(logoutData);
  }),

  // 获取菜单权限接口
  http.get('https://shop.trust-will.com/admin/index/rules', async ({ request }) => {
    await delay(200);

    const token = extractToken(request);

    // 验证 Token
    if (!token || !isValidToken(token)) {
      return HttpResponse.json(createErrorResponse('未登录或登录已过期', 401));
    }

    // 模拟菜单权限数据
    const menuRules = [
      {
        id: 1,
        name: 'dashboard',
        title: '仪表盘',
        path: '/dashboard',
        component: 'dashboard/index',
        icon: 'dashboard',
        children: [],
      },
      {
        id: 2,
        name: 'system',
        title: '系统管理',
        path: '/system',
        icon: 'system',
        children: [
          {
            id: 21,
            name: 'user',
            title: '用户管理',
            path: '/system/user',
            component: 'system/user/index',
          },
          {
            id: 22,
            name: 'role',
            title: '角色管理',
            path: '/system/role',
            component: 'system/role/index',
          },
        ],
      },
    ];

    return HttpResponse.json(createSuccessResponse(menuRules, '获取成功'));
  }),
];
