const TOKEN_STORAGE_KEY = 'access_token';
const TOKEN_UID_KEY = 'user_uid';

/**
 * H5版本的Google OAuth鉴权服务
 */
export class AuthService {
  /**
   * 检查用户登录状态
   * 包括处理OAuth回调和验证本地token
   */
  async checkLogin(): Promise<boolean> {
    // 检查URL中是否有OAuth回调参数
    const urlParams = new URLSearchParams(window.location.search);
    const accessToken = urlParams.get('access_token');
    const userId = urlParams.get('user_id');

    if (accessToken && userId) {
      // 处理OAuth回调
      try {
        this.setAccessToken(accessToken, userId);

        // 清理URL参数，避免重复处理
        const newUrl = window.location.pathname;
        window.history.replaceState(null, '', newUrl);

        console.log('OAuth登录成功，token已保存');
        return true;
      } catch (error) {
        console.error('处理OAuth回调失败:', error);
        return false;
      }
    }

    // 如果没有回调参数，检查本地存储的token
    try {
      const token = localStorage.getItem(TOKEN_STORAGE_KEY);
      return !!token;
    } catch (error) {
      console.log('本地token无效或已过期');
      return false;
    }
  }

  /**
   * 跳转到Google OAuth登录页面
   */
  async login(redirectPath?: string): Promise<void> {
    const { hostname, protocol, port } = window.location;
    let baseUrl = `${protocol}//${hostname}`;
    if (hostname === 'localhost') {
      baseUrl = `${protocol}//${hostname}:${port}`;
    }
    const redirectUrl = `https://api.bestaibest.ai/auth/google/authorize?redirect_url=${baseUrl}${redirectPath || ''}`;
    window.location.href = redirectUrl;
  }

  /**
   * 登出用户
   */
  async logout(): Promise<void> {
    try {
      this.clearAccessToken();
      console.log('用户已登出');
    } catch (error) {
      console.error('登出失败:', error);
    }
  }

  /**
   * 存储访问令牌和用户ID
   * 将OAuth访问令牌和用户ID保存到本地存储中
   * @param token OAuth访问令牌
   * @param uid 用户唯一标识
   */
  setAccessToken(token: string, uid: string): void {
    try {
      localStorage.setItem(TOKEN_STORAGE_KEY, token);
      localStorage.setItem(TOKEN_UID_KEY, uid);
      console.log('🔑 Access token and user ID stored successfully');
    } catch (error) {
      console.error('❌ Failed to store access token:', error);
    }
  }

  /**
   * 清除访问令牌和用户ID
   * 从本地存储中移除访问令牌和用户ID，通常在登出时调用
   */
  clearAccessToken(): void {
    try {
      localStorage.removeItem(TOKEN_STORAGE_KEY);
      localStorage.removeItem(TOKEN_UID_KEY);
      console.log('🗑️ Access token and user ID cleared successfully');
    } catch (error) {
      console.error('❌ Failed to clear access token:', error);
    }
  }

  /*
   * 获取认证头部
   * 自动从localStorage中读取访问令牌并添加到Authorization头部
   * @returns 认证头部对象
   */
  getAccessToken(): string | null {
    const token = localStorage.getItem(TOKEN_STORAGE_KEY);
    return token;
  }

  getUserId(): string | null {
    const userId = localStorage.getItem(TOKEN_UID_KEY);
    return userId;
  }
}

// 导出单例实例
export const auth = new AuthService();
