const { handleIncomingMessage } = require('./features/menu');
const { getUserData, updateUserData } = require('./utils/user');

// Mock WhatsApp socket
const mockSock = {
  sendMessage: async (phone, message) => {
    console.log(`📤 Sending to ${phone}:`, message.text || message.caption || 'Media message');
    return { key: { id: 'test-message-id' } };
  }
};

// Test function to simulate ticket type selection flow
async function testTicketTypeSelection() {
  const testPhone = '265991234567@s.whatsapp.net';

  console.log('🧪 Starting ticket type selection test...\n');

  try {
    // Step 1: Set up initial state
    console.log('📋 Step 1: Setting up test user with TICKETING_SELECT_TICKET_TYPE state');
    await updateUserData(testPhone, {
      state: 'TICKETING_SELECT_TICKET_TYPE',
      name: 'Test User',
      currentEvent: {
        product_id: '123',
        product_name: 'Zisomo Gospel Concert (Children Ticket)',
        product_price: '50',
        product_description: 'A wonderful gospel concert for children'
      },
      ticketData: {
        ticketTypes: [
          { product_price_name: 'Standard', product_price: '50' },
          { product_price_name: 'VIP', product_price: '51' },
          { product_price_name: 'VVIP', product_price: '52' }
        ]
      }
    });

    // Step 2: Test invalid selection
    console.log('\n📋 Step 2: Testing invalid ticket type selection');
    await handleIncomingMessage(mockSock, testPhone, '0', { pushName: 'Test User' });

    // Step 3: Test valid selection
    console.log('\n📋 Step 3: Testing valid ticket type selection (option 1)');
    await handleIncomingMessage(mockSock, testPhone, '1', { pushName: 'Test User' });

    // Step 4: Verify state transition
    console.log('\n📋 Step 4: Verifying state after selection');
    const userData = await getUserData(testPhone);
    console.log('Current state:', userData.state);
    console.log('Selected ticket type:', userData.ticketData?.selectedTicketType?.product_price_name);

    // Step 5: Test quantity input
    console.log('\n📋 Step 5: Testing quantity input (2 tickets)');
    await handleIncomingMessage(mockSock, testPhone, '2', { pushName: 'Test User' });

    // Step 6: Final state check
    console.log('\n📋 Step 6: Final state verification');
    const finalUserData = await getUserData(testPhone);
    console.log('Final state:', finalUserData.state);
    console.log('Quantity:', finalUserData.ticketData?.quantity);

    console.log('\n✅ Test completed successfully!');

  } catch (error) {
    console.error('❌ Test failed:', error);
  }
}

// Test function to simulate back navigation
async function testBackNavigation() {
  const testPhone = '265991234568@s.whatsapp.net';

  console.log('\n🧪 Starting back navigation test...\n');

  try {
    // Set up user in quantity state
    await updateUserData(testPhone, {
      state: 'TICKETING_QUANTITY',
      name: 'Test User 2',
      currentEvent: {
        product_id: '123',
        product_name: 'Test Event',
        product_price: '50'
      },
      ticketData: {
        selectedTicketType: { product_price_name: 'Standard', product_price: '50' },
        ticketTypes: [
          { product_price_name: 'Standard', product_price: '50' },
          { product_price_name: 'VIP', product_price: '100' }
        ]
      }
    });

    // Test back navigation from quantity to ticket type selection
    console.log('📋 Testing back navigation from quantity to ticket type selection');
    await handleIncomingMessage(mockSock, testPhone, 'back', { pushName: 'Test User 2' });

    // Verify state
    const userData = await getUserData(testPhone);
    console.log('State after back navigation:', userData.state);

    console.log('✅ Back navigation test completed!');

  } catch (error) {
    console.error('❌ Back navigation test failed:', error);
  }
}

// Run tests
async function runAllTests() {
  console.log('🚀 Running ticket type selection tests...\n');

  await testTicketTypeSelection();
  await testBackNavigation();

  console.log('\n🎉 All tests completed!');
  process.exit(0);
}

// Run if called directly
if (require.main === module) {
  runAllTests().catch(console.error);
}

module.exports = {
  testTicketTypeSelection,
  testBackNavigation
};
