/**
 * 用户认证相关API
 */

import { USE_MOCK } from '@/utils/config';
import { mockLoginResponse, mockUserInfo } from '@/mock';
import { setToken, setUserInfo } from '@/utils/auth';

export interface LoginParams {
  username: string;
  password: string;
}

export interface LoginResponse {
  token: string;
  userInfo: any;
}

/**
 * 登录
 */
export async function login(params: LoginParams): Promise<LoginResponse> {
  if (USE_MOCK) {
    // 模拟登录验证
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (params.username === 'admin' && params.password === '123456') {
          const response = {
            token: mockLoginResponse.token,
            userInfo: mockUserInfo
          };
          // 保存登录信息
          setToken(response.token);
          setUserInfo(response.userInfo);
          resolve(response);
        } else {
          reject(new Error('用户名或密码错误'));
        }
      }, 500);
    });
  }
  
  // 实际API调用
  const { post } = await import('@/utils/request');
  const response = await post<LoginResponse>('/auth/login', params);
  setToken(response.token);
  setUserInfo(response.userInfo);
  return response;
}

/**
 * 退出登录
 */
export async function logout(): Promise<void> {
  if (USE_MOCK) {
    return Promise.resolve();
  }
  
  const { post } = await import('@/utils/request');
  await post('/auth/logout');
}

/**
 * 获取当前用户信息
 */
export async function getCurrentUser(): Promise<any> {
  if (USE_MOCK) {
    return Promise.resolve(mockUserInfo);
  }
  
  const { get } = await import('@/utils/request');
  return get('/auth/user-info');
}

/**
 * 修改密码
 */
export async function changePassword(oldPassword: string, newPassword: string): Promise<void> {
  if (USE_MOCK) {
    return Promise.resolve();
  }
  
  const { post } = await import('@/utils/request');
  await post('/auth/change-password', { oldPassword, newPassword });
}
