/**
 * 认证服务
 * 处理用户登录、注册、登出等认证相关操作
 */

import { http, tokenManager, ApiError } from './api';
import type { AuthData, LoginRequest, RegisterRequest, UserInfo } from '../types/api';

// 重新导出 ApiErrorMessages 以便使用
export { ApiErrorMessages } from '../types/api';

/**
 * 从 JWT Token 解析用户信息
 */
function parseJwtPayload(token: string): UserInfo | null {
  try {
    // 移除 Bearer 前缀
    const actualToken = token.replace('Bearer ', '');
    const base64Payload = actualToken.split('.')[1];
    const payload = JSON.parse(atob(base64Payload));
    return payload as UserInfo;
  } catch {
    return null;
  }
}

/**
 * 认证服务
 */
export const authService = {
  /**
   * 用户登录
   */
  async login(credentials: LoginRequest): Promise<{ user: UserInfo; token: string; expiresAt: number }> {
    const response = await http.post<AuthData>('/user/login', credentials, { skipAuth: true });

    if (!response.data) {
      throw new ApiError(-1, '登录失败，请重试');
    }

    const { token, expires_at } = response.data;

    // 存储 Token 和 email
    tokenManager.setToken(token, expires_at, credentials.email);

    // 解析用户信息
    const user = parseJwtPayload(token);
    if (!user) {
      throw new ApiError(-1, 'Token 解析失败');
    }

    // 补充 email 和 id 兼容字段
    const userWithEmail: UserInfo = {
      ...user,
      email: credentials.email,
      id: String(user.user_id),
    };

    return {
      user: userWithEmail,
      token,
      expiresAt: expires_at,
    };
  },

  /**
   * 用户注册
   * 注意：业务错误码 (code !== 200) 已在 api.ts 中统一处理，会抛出 ApiError
   */
  async register(credentials: RegisterRequest): Promise<{ user: UserInfo; token: string; expiresAt: number }> {
    const response = await http.post<AuthData>('/user/register', credentials, { skipAuth: true });

    if (!response.data) {
      throw new ApiError(-1, '注册失败，请重试');
    }

    const { token, expires_at } = response.data;

    // 存储 Token 和 email
    tokenManager.setToken(token, expires_at, credentials.email);

    // 解析用户信息
    const user = parseJwtPayload(token);
    if (!user) {
      throw new ApiError(-1, 'Token 解析失败');
    }

    // 补充 email 和 id 兼容字段
    const userWithEmail: UserInfo = {
      ...user,
      email: credentials.email,
      id: String(user.user_id),
    };

    return {
      user: userWithEmail,
      token,
      expiresAt: expires_at,
    };
  },

  /**
   * 用户登出
   */
  logout(): void {
    tokenManager.removeToken();
  },

  /**
   * 检查是否已登录
   */
  isAuthenticated(): boolean {
    return tokenManager.isTokenValid();
  },

  /**
   * 获取当前存储的 Token
   */
  getToken(): string | null {
    return tokenManager.getToken();
  },

  /**
   * 从存储的 Token 恢复用户会话
   */
  restoreSession(): { user: UserInfo; token: string; expiresAt: number } | null {
    const token = tokenManager.getToken();
    const expiresAt = tokenManager.getExpiresAt();
    const email = tokenManager.getEmail();

    if (!token || !expiresAt || !tokenManager.isTokenValid()) {
      tokenManager.removeToken();
      return null;
    }

    const parsedUser = parseJwtPayload(token);
    if (!parsedUser) {
      tokenManager.removeToken();
      return null;
    }

    // 补充 email 和 id 兼容字段
    const user: UserInfo = {
      ...parsedUser,
      email: email || '',
      id: String(parsedUser.user_id),
    };

    return {
      user,
      token,
      expiresAt,
    };
  },
};

export { ApiError };
export default authService;

