const axios = require('axios');

// Test configuration
const BASE_URL = 'http://localhost:3003/api/templates';
const TEST_USER_ID = '550e8400-e29b-41d4-a716-446655440000'; // Sample UUID

// Test template data
const testTemplate = {
  type: 'test-duplicate-template',
  title: 'Test Duplicate Template',
  description: 'This is a test template for duplicate prevention',
  category: 'test',
  icon: 'test-icon',
  gradient: 'bg-blue-500',
  border: 'border-blue-200',
  text: 'text-blue-800',
  subtext: 'text-blue-600',
  isCustom: true,
  user_id: TEST_USER_ID,
  complexity: 'medium'
};

async function testDuplicatePrevention() {
  console.log('🧪 Testing Template Duplicate Prevention\n');
  
  try {
    // Test 1: Create first template (should succeed)
    console.log('📝 Test 1: Creating first template...');
    const response1 = await axios.post(BASE_URL, testTemplate);
    console.log('✅ First template created successfully:', response1.data.data.id);
    const firstTemplateId = response1.data.data.id;
    
    // Test 2: Try to create exact duplicate (should fail)
    console.log('\n📝 Test 2: Attempting to create exact duplicate...');
    try {
      await axios.post(BASE_URL, testTemplate);
      console.log('❌ ERROR: Duplicate was allowed when it should have been prevented!');
    } catch (error) {
      if (error.response && error.response.status === 409) {
        console.log('✅ Duplicate correctly prevented:', error.response.data.message);
        console.log('   Existing template info:', error.response.data.existing_template);
      } else {
        console.log('❌ Unexpected error:', error.response?.data || error.message);
      }
    }
    
    // Test 3: Try with same title but different type (should fail for same user)
    console.log('\n📝 Test 3: Attempting same title, different type...');
    const sameTitle = { ...testTemplate, type: 'different-type-same-title' };
    try {
      await axios.post(BASE_URL, sameTitle);
      console.log('❌ ERROR: Same title duplicate was allowed!');
    } catch (error) {
      if (error.response && error.response.status === 409) {
        console.log('✅ Same title duplicate correctly prevented:', error.response.data.message);
      } else {
        console.log('❌ Unexpected error:', error.response?.data || error.message);
      }
    }
    
    // Test 4: Try with same type but different title (should fail)
    console.log('\n📝 Test 4: Attempting same type, different title...');
    const sameType = { ...testTemplate, title: 'Different Title Same Type' };
    try {
      await axios.post(BASE_URL, sameType);
      console.log('❌ ERROR: Same type duplicate was allowed!');
    } catch (error) {
      if (error.response && error.response.status === 409) {
        console.log('✅ Same type duplicate correctly prevented:', error.response.data.message);
      } else {
        console.log('❌ Unexpected error:', error.response?.data || error.message);
      }
    }
    
    // Test 5: Different user should be able to create similar template
    console.log('\n📝 Test 5: Different user creating similar template...');
    const differentUser = { 
      ...testTemplate, 
      user_id: '550e8400-e29b-41d4-a716-446655440001', // Different UUID
      type: 'test-duplicate-template-user2'
    };
    try {
      const response5 = await axios.post(BASE_URL, differentUser);
      console.log('✅ Different user can create similar template:', response5.data.data.id);
    } catch (error) {
      console.log('❌ Different user blocked unexpectedly:', error.response?.data || error.message);
    }
    
    // Cleanup: Delete test templates
    console.log('\n🧹 Cleaning up test templates...');
    try {
      await axios.delete(`${BASE_URL}/${firstTemplateId}`);
      console.log('✅ Cleanup completed');
    } catch (error) {
      console.log('⚠️ Cleanup failed:', error.message);
    }
    
  } catch (error) {
    console.log('❌ Test setup failed:', error.response?.data || error.message);
    console.log('💡 Make sure the template service is running on port 3003');
  }
}

// Run the test
testDuplicatePrevention();
