/**
 * 认证模块 - 处理 Google OAuth 登录
 */

// 从 config.js 读取 API 地址
const API_BASE_URL = typeof CONFIG !== 'undefined' ? CONFIG.API_BASE_URL : 'http://localhost:3001';

class AuthManager {
  constructor() {
    this.token = null;
    this.user = null;
    this.subscription = null;
  }

  /**
   * 初始化 - 从 storage 加载 token
   */
  async init() {
    const data = await chrome.storage.sync.get(['authToken', 'user', 'subscription']);
    this.token = data.authToken || null;
    this.user = data.user || null;
    this.subscription = data.subscription || null;
    return this.isLoggedIn();
  }

  /**
   * 检查是否已登录
   */
  isLoggedIn() {
    return !!this.token && !!this.user;
  }

  /**
   * 启动 Google OAuth 登录流程
   */
  async startGoogleLogin() {
    try {

      // 1. 从后端获取 OAuth URL
      const url = `${API_BASE_URL}/api/auth/google/url`;
      const response = await fetch(url, { method: 'GET' });
      // 打印关键响应头（调试 CORS）
      try {
      } catch (e) {}

      if (!response.ok) {
        const text = await response.text().catch(() => '');
        throw new Error(`Fetch oauth url failed: ${response.status} ${response.statusText}`);
      }

      const { authUrl } = await response.json();

      if (!authUrl || typeof authUrl !== 'string') {
        throw new Error('Invalid authUrl from server');
      }

      // 2. 打开弹框样式的授权窗口
      const width = 450;
      const height = 550;
      const left = (screen.width / 2) - (width / 2);
      const top = (screen.height / 2) - (height / 2);

      const authWindow = window.open(
        authUrl,
        'Google Login',
        `width=${width},height=${height},left=${left},top=${top},toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no`
      );
      if (!authWindow) {
        throw new Error('Popup blocked');
      }

      // 3. 轮询检查登录结果
      return new Promise((resolve, reject) => {
        let checkInterval = null;
        let timeoutId = null;
        let windowClosed = false;

        // 轮询检查登录结果
        const checkLoginResult = async () => {
          try {
            // 检查窗口是否关闭（使用 try-catch 避免 COOP 策略错误）
            let isClosed = false;
            try {
              isClosed = authWindow && authWindow.closed;
            } catch (e) {
              // COOP 策略阻止访问 window.closed，假设窗口已关闭
              isClosed = true;
            }
            
            if (isClosed && !windowClosed) {
              windowClosed = true;
              
              // 等待2秒让后端处理完成
              setTimeout(async () => {
                try {
                  // 尝试获取所有待处理的登录结果
                  const response = await fetch(`${API_BASE_URL}/api/auth/pending-logins`);
                  if (response.ok) {
                    const { logins } = await response.json();
                    
                    // 找到最新的登录结果
                    if (logins && logins.length > 0) {
                      const latestLogin = logins[0]; // 最新的登录
                      
                      // 保存到 storage
                      await this.saveAuthData(latestLogin);
                      
                      if (checkInterval) clearInterval(checkInterval);
                      if (timeoutId) clearTimeout(timeoutId);
                      resolve(latestLogin);
                      return;
                    }
                  }
                } catch (error) {
                }
              }, 2000);
            }
          } catch (error) {
          }
        };

        // 每2秒检查一次
        checkInterval = setInterval(checkLoginResult, 2000);

        // 超时处理（60秒）
        timeoutId = setTimeout(() => {
          if (checkInterval) clearInterval(checkInterval);
          reject(new Error('Login timeout'));
        }, 60000);

        // 立即检查一次
        checkLoginResult();
      });
    } catch (error) {
      throw error;
    }
  }

  /**
   * 保存认证数据
   */
  async saveAuthData(loginData) {
    this.token = loginData.token;
    this.user = loginData.user;
    this.subscription = loginData.subscription;

    await chrome.storage.sync.set({
      authToken: this.token,
      user: this.user,
      subscription: this.subscription,
    });

  }

  /**
   * 验证 Token 并获取最新用户信息
   */
  async verifyToken() {
    if (!this.token) {
      throw new Error('No token available');
    }

    try {
      const response = await fetch(`${API_BASE_URL}/api/auth/me`, {
        headers: {
          'Authorization': `Bearer ${this.token}`,
        },
      });

      if (!response.ok) {
        throw new Error('Token verification failed');
      }

      const data = await response.json();
      
      this.user = data.user;
      this.subscription = data.subscription;

      await chrome.storage.sync.set({
        user: this.user,
        subscription: this.subscription,
      });

      return data;
    } catch (error) {
      await this.logout();
      throw error;
    }
  }

  /**
   * 激活试用
   */
  async activateTrial(activationCode) {
    if (!this.token) {
      throw new Error('Not logged in');
    }

    try {
      const response = await fetch(`${API_BASE_URL}/api/auth/activate-trial`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.token}`,
        },
        body: JSON.stringify({ activationCode }),
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || 'Activation failed');
      }

      const data = await response.json();
      this.subscription = data.subscription;

      await chrome.storage.sync.set({
        subscription: this.subscription,
      });

      return data;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 登出
   */
  async logout() {
    this.token = null;
    this.user = null;
    this.subscription = null;

    await chrome.storage.sync.remove(['authToken', 'user', 'subscription']);

  }

  /**
   * 获取用户信息
   */
  getUser() {
    return this.user;
  }

  /**
   * 获取订阅信息
   */
  getSubscription() {
    return this.subscription;
  }

  /**
   * 检查是否有访问权限
   */
  hasAccess() {
    if (!this.subscription) return false;
    
    const status = this.subscription.status;
    if (status === 'inactive') return false;

    if (this.subscription.expiresAt) {
      const expiresAt = new Date(this.subscription.expiresAt);
      if (expiresAt < new Date()) {
        return false;
      }
    }

    return ['trial', 'active'].includes(status);
  }
}

// 导出单例
const authManager = new AuthManager();

