const axios = require('axios');

const API_BASE_URL = 'http://localhost:3000/api';

// Test user credentials (you may need to adjust these based on your database)
const TEST_USER = {
  mobile_number: '9876543210',
  password: 'password123'
};

async function testAPI() {
  try {
    console.log('🔍 Testing LuckyChit API...\n');

    // Step 1: Test health endpoint
    console.log('1. Testing health endpoint...');
    const healthResponse = await axios.get('http://localhost:3000/health');
    console.log('✅ Health check passed:', healthResponse.data.message);
    console.log('');

    // Step 2: Login to get token
    console.log('2. Attempting login...');
    let token;
    try {
      const loginResponse = await axios.post(`${API_BASE_URL}/auth/login`, TEST_USER);
      token = loginResponse.data.data.token;
      console.log('✅ Login successful');
      console.log('User:', loginResponse.data.data.user.full_name);
      console.log('');
    } catch (loginError) {
      console.log('❌ Login failed:', loginError.response?.data?.message || loginError.message);
      console.log('💡 You may need to create a test user first');
      console.log('');
      
      // Try to create a test user
      console.log('3. Attempting to create test user...');
      try {
        const createResponse = await axios.post(`${API_BASE_URL}/auth/create-member`, {
          mobile_number: TEST_USER.mobile_number,
          full_name: 'Test User'
        });
        console.log('✅ Test user created successfully');
        console.log('Password:', createResponse.data.data.temp_password);
        console.log('');
        
        // Try login again
        console.log('4. Attempting login with new user...');
        const loginResponse2 = await axios.post(`${API_BASE_URL}/auth/login`, {
          mobile_number: TEST_USER.mobile_number,
          password: createResponse.data.data.temp_password
        });
        token = loginResponse2.data.data.token;
        console.log('✅ Login successful with new user');
        console.log('');
      } catch (createError) {
        console.log('❌ Failed to create test user:', createError.response?.data?.message || createError.message);
        console.log('💡 Please create a user manually or check the database');
        return;
      }
    }

    // Step 3: Test chit groups endpoint
    console.log('5. Testing chit groups endpoint...');
    try {
      const groupsResponse = await axios.get(`${API_BASE_URL}/chit-groups/manager`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      console.log('✅ Chit groups endpoint working');
      console.log('Groups found:', groupsResponse.data.data?.chitGroups?.length || 0);
      console.log('');
      
      // If there are groups, test the specific endpoints
      if (groupsResponse.data.data?.chitGroups?.length > 0) {
        const groupId = groupsResponse.data.data.chitGroups[0].id;
        console.log(`6. Testing specific group endpoints for group: ${groupId}`);
        
        // Test stats endpoint
        try {
          const statsResponse = await axios.get(`${API_BASE_URL}/chit-groups/${groupId}/stats`, {
            headers: { Authorization: `Bearer ${token}` }
          });
          console.log('✅ Stats endpoint working');
          console.log('Stats:', statsResponse.data.data);
        } catch (statsError) {
          console.log('❌ Stats endpoint failed:', statsError.response?.data?.message || statsError.message);
        }
        
        // Test financial data endpoint
        try {
          const financialResponse = await axios.get(`${API_BASE_URL}/chit-groups/${groupId}/financial-data`, {
            headers: { Authorization: `Bearer ${token}` }
          });
          console.log('✅ Financial data endpoint working');
          console.log('Financial entries:', financialResponse.data.data?.financial_data?.length || 0);
        } catch (financialError) {
          console.log('❌ Financial data endpoint failed:', financialError.response?.data?.message || financialError.message);
        }
      } else {
        console.log('💡 No chit groups found. Create a chit group first to test specific endpoints.');
      }
      
    } catch (groupsError) {
      console.log('❌ Chit groups endpoint failed:', groupsError.response?.data?.message || groupsError.message);
    }

    console.log('\n🎉 API testing completed!');

  } catch (error) {
    console.error('❌ Test failed:', error.message);
    if (error.response) {
      console.error('Response data:', error.response.data);
    }
  }
}

// Run the test
testAPI();
