/*
 * Session Auto Login Service - 简化的URL参数处理服务
 */

import {logger} from '../logger';
import sessionStorage from '../sessionStorage';
import {AppStoragesManager} from '../appManagers/appStoragesManager';
import commonStateStorage from '../commonStateStorage';
import EncryptedStorageLayer from '../encryptedStorageLayer';
import {getCommonDatabaseState} from '../../config/databases/state';
import CacheStorageController from '../files/cacheStorage';

export class SessionAutoLoginService {
  private log = logger('[session-auto-login-service]');

  /**
   * 解析URL参数中的data值
   */
  public parseUrlParams(): string | null {
    try {
      const urlParams = new URLSearchParams(window.location.search);
      const data = urlParams.get('data');

      if(data) {
        this.log('Found data parameter in URL:', data.substring(0, 50) + '...');
        return data;
      }

      return null;
    } catch(error) {
      this.log('Error parsing URL parameters:', error);
      return null;
    }
  }

  /**
   * 清除URL中的data参数
   */
  public clearUrlParams(): void {
    try {
      const url = new URL(window.location.href);
      url.searchParams.delete('data');

      // 使用replaceState避免在浏览器历史中留下记录
      window.history.replaceState({}, '', url.toString());

      this.log('Cleared data parameter from URL');
    } catch(error) {
      this.log('Error clearing URL parameters:', error);
    }
  }

  /**
   * 检查是否存在旧的会话数据
   */
  public async hasExistingSessionData(): Promise<boolean> {
    try {
      // 检查 sessionStorage 中是否有账号数据
      const account1 = await sessionStorage.get('account1');
      const dc = await sessionStorage.get('dc');
      const userAuth = await sessionStorage.get('user_auth');

      // 检查 localStorage 中是否有相关数据
      const hasLocalStorageData = ['dc', 'dcId', 'auth_key', 'user_id'].some(key =>
        localStorage.getItem(key) !== null
      );

      return !!(account1 || dc || userAuth || hasLocalStorageData);
    } catch(error) {
      this.log('Error checking existing session data:', error);
      return false;
    }
  }

  /**
   * 清理所有会话数据，为新登录做准备
   */
  public async clearAllSessionData(): Promise<void> {
    try {
      this.log('Starting to clear all session data...');

      // 清理 sessionStorage 中的关键数据
      const sessionKeys: string[] = [
        'account1',
        'account2',
        'account3',
        'account4',
        'dc',
        'server_time_offset',
        'xt_instance',
        'user_auth',
        'k_build',
        'auth_key_fingerprint',
        'current_account',
        'number_of_accounts',
        'previous_account',
        'should_animate_auth',
        'should_animate_main'
      ];

      // 添加所有 DC 相关的键
      for(let i = 1; i <= 5; ++i) {
        sessionKeys.push(`dc${i}_server_salt`);
        sessionKeys.push(`dc${i}_auth_key`);
        sessionKeys.push(`dc${i}_hash`);
      }

      // 删除 sessionStorage 中的数据
      const validSessionKeys = sessionKeys.filter(key =>
        key === 'account1' || key === 'account2' || key === 'account3' || key === 'account4' ||
        key === 'dc' || key === 'user_auth' || key === 'server_time_offset' ||
        key === 'xt_instance' || key === 'k_build' || key === 'auth_key_fingerprint' ||
        key === 'current_account' || key === 'number_of_accounts' ||
        key === 'previous_account' || key === 'should_animate_auth' ||
        key === 'should_animate_main' ||
        key.startsWith('dc') && (key.includes('_server_salt') || key.includes('_auth_key') || key.includes('_hash'))
      );

      await Promise.all(validSessionKeys.map(key => sessionStorage.delete(key as any)));

      // 清理所有账号的存储数据
      await AppStoragesManager.clearAllStoresForAccount(1);
      await AppStoragesManager.clearSessionStores();

      // 清理通用状态存储
      await commonStateStorage.clear();

      // 清理加密存储
      const encryptedStorage = EncryptedStorageLayer.getInstance(getCommonDatabaseState(), 'localStorage__encrypted');
      await encryptedStorage.clear();

      // 清理缓存存储
      await CacheStorageController.deleteAllStorages();

      // 清理 localStorage 中的相关数据
      const localStorageKeys = [
        'autoLoginFromUrl',
        'dc',
        'dcId',
        'serverTimeOffset',
        'auth_key',
        'user_id',
        'userId',
        'session'
      ];

      localStorageKeys.forEach(key => {
        try {
          localStorage.removeItem(key);
        } catch(e) {
          this.log(`Failed to remove localStorage key ${key}:`, e);
        }
      });

      this.log('Successfully cleared all session data');
    } catch(error) {
      this.log('Error clearing session data:', error);
      throw error;
    }
  }
}

// 导出单例实例
export const sessionAutoLoginService = new SessionAutoLoginService();
