/**
 * Test script to demonstrate Chrome extension user ID functionality
 * This simulates how a Chrome extension would interact with the remote server
 * and shows how user IDs are generated and used.
 */

import WebSocket from 'ws';

class ChromeExtensionUserIdTest {
  constructor(serverUrl = 'ws://127.0.0.1:3001/chrome') {
    this.serverUrl = serverUrl;
    this.ws = null;
    this.userId = null;
    this.connected = false;
  }

  /**
   * Generate a user ID in the same format as the Chrome extension
   */
  generateUserId() {
    const timestamp = Date.now();
    const randomSuffix = Math.random().toString(36).substring(2, 15);
    return `user_${timestamp}_${randomSuffix}`;
  }

  /**
   * Connect to the remote server and send user ID
   */
  async connect() {
    return new Promise((resolve, reject) => {
      console.log(`🔗 Connecting to remote server: ${this.serverUrl}`);

      this.ws = new WebSocket(this.serverUrl);

      this.ws.on('open', () => {
        console.log('✅ Connected to remote server');
        this.connected = true;

        // Generate unique user ID (simulating Chrome extension behavior)
        this.userId = this.generateUserId();
        console.log(`👤 Generated User ID: ${this.userId}`);

        // Send connection info with user ID (simulating Chrome extension)
        const connectionInfo = {
          type: 'connection_info',
          userId: this.userId,
          userAgent: 'TestChromeExtension/1.0',
          timestamp: Date.now(),
          extensionId: 'test-extension-user-id-demo',
        };

        console.log('📤 Sending connection info with user ID...');
        this.ws.send(JSON.stringify(connectionInfo));

        resolve();
      });

      this.ws.on('message', (data) => {
        try {
          const message = JSON.parse(data.toString());
          console.log('📥 Received message:', message);

          if (message.type === 'connection_confirmed') {
            console.log('✅ Connection confirmed by server');
            console.log(`🎯 Server assigned session: ${message.sessionId}`);
            console.log(`👤 Server confirmed user ID: ${message.userId}`);
          }
        } catch (error) {
          console.error('❌ Failed to parse message:', error);
        }
      });

      this.ws.on('error', (error) => {
        console.error('❌ WebSocket error:', error.message);
        reject(error);
      });

      this.ws.on('close', () => {
        console.log('🔌 Connection closed');
        this.connected = false;
      });
    });
  }

  /**
   * Get the current user ID
   */
  getCurrentUserId() {
    return this.userId;
  }

  /**
   * Simulate getting user ID from storage (like Chrome extension would)
   */
  getUserIdFromStorage() {
    // In real Chrome extension, this would be:
    // const result = await chrome.storage.local.get(['chrome_extension_user_id']);
    // return result.chrome_extension_user_id;

    console.log("📦 Simulating chrome.storage.local.get(['chrome_extension_user_id'])");
    return this.userId;
  }

  /**
   * Disconnect from the server
   */
  disconnect() {
    if (this.ws) {
      console.log('🔌 Disconnecting from remote server...');
      this.ws.close();
    }
  }

  /**
   * Test the complete user ID workflow
   */
  async testUserIdWorkflow() {
    try {
      console.log('🚀 Starting Chrome Extension User ID Test\n');

      // Step 1: Connect to server
      await this.connect();

      // Step 2: Demonstrate user ID access methods
      console.log('\n📋 User ID Access Methods:');
      console.log(`1. Direct access: ${this.getCurrentUserId()}`);
      console.log(`2. Storage simulation: ${this.getUserIdFromStorage()}`);

      // Step 3: Show user ID format and properties
      console.log('\n🔍 User ID Analysis:');
      const userId = this.getCurrentUserId();
      console.log(`   Full ID: ${userId}`);
      console.log(`   Length: ${userId.length} characters`);
      console.log(`   Format: user_{timestamp}_{random}`);

      // Extract timestamp
      const parts = userId.split('_');
      if (parts.length >= 3) {
        const timestamp = parseInt(parts[1]);
        const date = new Date(timestamp);
        console.log(`   Generated at: ${date.toISOString()}`);
        console.log(`   Random suffix: ${parts[2]}`);
      }

      // Step 4: Demonstrate truncated display (like in popup)
      const truncated =
        userId.length > 20
          ? `${userId.substring(0, 8)}...${userId.substring(userId.length - 8)}`
          : userId;
      console.log(`   Truncated display: ${truncated}`);

      // Step 5: Wait a bit then disconnect
      console.log('\n⏳ Waiting 3 seconds before disconnecting...');
      setTimeout(() => {
        this.disconnect();
        console.log('\n✅ User ID test completed successfully!');

        console.log('\n📖 Next Steps:');
        console.log('1. Load the Chrome extension in your browser');
        console.log('2. Connect to the remote server via the popup');
        console.log('3. Your user ID will be displayed in the popup interface');
        console.log('4. Click the 📋 button to copy your user ID');
        console.log('5. Use the user ID for session management and routing');

        process.exit(0);
      }, 3000);
    } catch (error) {
      console.error('❌ Test failed:', error.message);
      process.exit(1);
    }
  }
}

// Run the test if this script is executed directly
const test = new ChromeExtensionUserIdTest();
test.testUserIdWorkflow();

export default ChromeExtensionUserIdTest;
