// Test file for Favorites API
// Run with: node test-favorites-api.js

import axios from 'axios';

const API_URL = 'http://localhost:5000/api/favorite';
let authToken = 'YOUR_AUTH_TOKEN_HERE'; // Replace with actual token

// Test configuration
const testConfig = {
  headers: {
    'Authorization': `Bearer ${authToken}`,
    'Content-Type': 'application/json'
  }
};

// Color codes for console output
const colors = {
  reset: '\x1b[0m',
  green: '\x1b[32m',
  red: '\x1b[31m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m'
};

function log(message, color = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

// Test 1: Add to favorites
async function testAddToFavorites() {
  log('\n🧪 Test 1: Add to Favorites', 'blue');
  try {
    const response = await axios.post(
      API_URL,
      {
        itemType: 'nominee',
        itemId: '6123456789abcdef01234567' // Replace with real ID
      },
      testConfig
    );
    
    if (response.data.success) {
      log('✅ PASS: Successfully added to favorites', 'green');
      console.log(response.data);
      return response.data.favorite._id;
    } else {
      log('❌ FAIL: Failed to add to favorites', 'red');
      console.log(response.data);
    }
  } catch (error) {
    log('❌ ERROR: ' + error.response?.data?.message || error.message, 'red');
    console.log(error.response?.data);
  }
}

// Test 2: Check duplicate prevention
async function testDuplicatePrevention() {
  log('\n🧪 Test 2: Duplicate Prevention', 'blue');
  try {
    const response = await axios.post(
      API_URL,
      {
        itemType: 'nominee',
        itemId: '6123456789abcdef01234567' // Same ID as Test 1
      },
      testConfig
    );
    
    if (response.status === 409) {
      log('✅ PASS: Duplicate correctly prevented', 'green');
    } else {
      log('❌ FAIL: Duplicate was allowed', 'red');
    }
    console.log(response.data);
  } catch (error) {
    if (error.response?.status === 409) {
      log('✅ PASS: Duplicate correctly prevented (409 Conflict)', 'green');
      console.log(error.response.data);
    } else {
      log('❌ ERROR: ' + error.response?.data?.message || error.message, 'red');
    }
  }
}

// Test 3: Check if favorited
async function testCheckFavorite() {
  log('\n🧪 Test 3: Check if Item is Favorited', 'blue');
  try {
    const itemId = '6123456789abcdef01234567'; // Replace with real ID
    const response = await axios.get(
      `${API_URL}/${itemId}`,
      testConfig
    );
    
    if (response.data.success && response.data.found === true) {
      log('✅ PASS: Item correctly identified as favorited', 'green');
    } else if (response.data.success && response.data.found === false) {
      log('✅ PASS: Item correctly identified as not favorited', 'green');
    } else {
      log('❌ FAIL: Unexpected response', 'red');
    }
    console.log(response.data);
  } catch (error) {
    log('❌ ERROR: ' + error.response?.data?.message || error.message, 'red');
  }
}

// Test 4: Get all favorites
async function testGetAllFavorites() {
  log('\n🧪 Test 4: Get All Favorites', 'blue');
  try {
    const response = await axios.get(API_URL, testConfig);
    
    if (response.data.success && Array.isArray(response.data.favorites)) {
      log(`✅ PASS: Retrieved ${response.data.count} favorites`, 'green');
      console.log(`Total: ${response.data.count}`);
      response.data.favorites.forEach((fav, index) => {
        console.log(`${index + 1}. Type: ${fav.itemType}, ID: ${fav._id}`);
      });
    } else {
      log('❌ FAIL: Invalid response format', 'red');
    }
  } catch (error) {
    log('❌ ERROR: ' + error.response?.data?.message || error.message, 'red');
  }
}

// Test 5: Remove from favorites
async function testRemoveFromFavorites() {
  log('\n🧪 Test 5: Remove from Favorites', 'blue');
  try {
    const response = await axios.delete(
      API_URL,
      {
        ...testConfig,
        data: {
          itemType: 'nominee',
          itemId: '6123456789abcdef01234567' // Replace with real ID
        }
      }
    );
    
    if (response.data.success) {
      log('✅ PASS: Successfully removed from favorites', 'green');
      console.log(response.data);
    } else {
      log('❌ FAIL: Failed to remove from favorites', 'red');
    }
  } catch (error) {
    log('❌ ERROR: ' + error.response?.data?.message || error.message, 'red');
    console.log(error.response?.data);
  }
}

// Test 6: Invalid itemType
async function testInvalidItemType() {
  log('\n🧪 Test 6: Invalid ItemType Validation', 'blue');
  try {
    const response = await axios.post(
      API_URL,
      {
        itemType: 'invalid_type',
        itemId: '6123456789abcdef01234567'
      },
      testConfig
    );
    
    log('❌ FAIL: Invalid itemType was accepted', 'red');
    console.log(response.data);
  } catch (error) {
    if (error.response?.status === 400) {
      log('✅ PASS: Invalid itemType correctly rejected', 'green');
      console.log(error.response.data);
    } else {
      log('❌ ERROR: Unexpected error', 'red');
    }
  }
}

// Test 7: Invalid itemId format
async function testInvalidItemId() {
  log('\n🧪 Test 7: Invalid ItemId Format Validation', 'blue');
  try {
    const response = await axios.post(
      API_URL,
      {
        itemType: 'nominee',
        itemId: 'invalid_id_format'
      },
      testConfig
    );
    
    log('❌ FAIL: Invalid itemId was accepted', 'red');
    console.log(response.data);
  } catch (error) {
    if (error.response?.status === 400) {
      log('✅ PASS: Invalid itemId correctly rejected', 'green');
      console.log(error.response.data);
    } else {
      log('❌ ERROR: Unexpected error', 'red');
    }
  }
}

// Test 8: Missing authentication
async function testMissingAuth() {
  log('\n🧪 Test 8: Missing Authentication', 'blue');
  try {
    const response = await axios.get(API_URL);
    log('❌ FAIL: Request without auth was accepted', 'red');
  } catch (error) {
    if (error.response?.status === 401) {
      log('✅ PASS: Unauthorized request correctly rejected', 'green');
      console.log(error.response.data);
    } else {
      log('❌ ERROR: Unexpected error', 'red');
    }
  }
}

// Run all tests
async function runAllTests() {
  log('🚀 Starting Favorites API Tests', 'yellow');
  log('='.repeat(50), 'yellow');
  
  if (authToken === 'YOUR_AUTH_TOKEN_HERE') {
    log('\n⚠️  WARNING: Please set a valid authToken in the test file!', 'yellow');
    log('Get your token by logging in and checking localStorage.authToken\n', 'yellow');
    return;
  }
  
  await testAddToFavorites();
  await new Promise(resolve => setTimeout(resolve, 500)); // Wait 500ms between tests
  
  await testDuplicatePrevention();
  await new Promise(resolve => setTimeout(resolve, 500));
  
  await testCheckFavorite();
  await new Promise(resolve => setTimeout(resolve, 500));
  
  await testGetAllFavorites();
  await new Promise(resolve => setTimeout(resolve, 500));
  
  await testRemoveFromFavorites();
  await new Promise(resolve => setTimeout(resolve, 500));
  
  await testInvalidItemType();
  await new Promise(resolve => setTimeout(resolve, 500));
  
  await testInvalidItemId();
  await new Promise(resolve => setTimeout(resolve, 500));
  
  await testMissingAuth();
  
  log('\n' + '='.repeat(50), 'yellow');
  log('✅ All tests completed!', 'yellow');
}

// Execute tests
runAllTests().catch(console.error);
