import dotenv from 'dotenv';
import { uploadToDropbox, generateUniqueFilename, getFileExtensionFromBase64 } from './utils/dropboxService.js';

// Load environment variables
dotenv.config();

// Sample base64 image (1x1 red pixel PNG)
const sampleBase64Image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==';

async function testDropboxConnection() {
  console.log('🧪 Testing Dropbox Integration with OAuth2...\n');

  // Check if OAuth2 credentials are set
  if (!process.env.DROPBOX_APP_KEY || process.env.DROPBOX_APP_KEY === 'YOUR_APP_KEY_HERE') {
    console.error('❌ DROPBOX_APP_KEY is not set in .env file');
    console.log('\n📝 Follow the setup guide in DROPBOX_CREDENTIALS_SETUP.md\n');
    process.exit(1);
  }
  
  if (!process.env.DROPBOX_APP_SECRET || process.env.DROPBOX_APP_SECRET === 'YOUR_APP_SECRET_HERE') {
    console.error('❌ DROPBOX_APP_SECRET is not set in .env file');
    console.log('\n📝 Follow the setup guide in DROPBOX_CREDENTIALS_SETUP.md\n');
    process.exit(1);
  }
  
  if (!process.env.DROPBOX_REFRESH_TOKEN || process.env.DROPBOX_REFRESH_TOKEN === 'YOUR_REFRESH_TOKEN_HERE') {
    console.error('❌ DROPBOX_REFRESH_TOKEN is not set in .env file');
    console.log('\n📝 Follow the setup guide in DROPBOX_CREDENTIALS_SETUP.md\n');
    process.exit(1);
  }

  console.log('✅ OAuth2 credentials found in environment variables');
  console.log(`   App Key: ${process.env.DROPBOX_APP_KEY}`);
  console.log(`   App Secret: ${process.env.DROPBOX_APP_SECRET.substring(0, 5)}...`);
  console.log(`   Refresh Token: ${process.env.DROPBOX_REFRESH_TOKEN.substring(0, 10)}...`);
  console.log('');

  try {
    console.log('📤 Attempting to upload test image...');
    
    // Generate unique filename
    const filename = generateUniqueFilename('test-image.png', 'test');
    console.log(`   Generated filename: ${filename}`);
    
    // Upload to Dropbox
    const startTime = Date.now();
    const url = await uploadToDropbox(sampleBase64Image, filename, '/test-uploads');
    const uploadTime = Date.now() - startTime;
    
    console.log('\n✅ Upload successful!');
    console.log(`   Upload time: ${uploadTime}ms`);
    console.log(`   Dropbox URL: ${url}`);
    console.log('');
    
    console.log('🔍 Testing URL access...');
    const fetch = (await import('node-fetch')).default;
    const response = await fetch(url);
    
    if (response.ok) {
      console.log('✅ File is accessible via URL');
      console.log(`   Status: ${response.status} ${response.statusText}`);
      console.log(`   Content-Type: ${response.headers.get('content-type')}`);
    } else {
      console.log('⚠️  File uploaded but URL might not be immediately accessible');
      console.log(`   Status: ${response.status} ${response.statusText}`);
    }
    
    console.log('\n✅ All tests passed!');
    console.log('\n📁 Check your Dropbox:');
    console.log('   Look for file in: /test-uploads/' + filename);
    console.log('   (or /Apps/YourAppName/test-uploads/ if using App folder access)');
    console.log('');
    console.log('🎉 Dropbox integration is working correctly!');
    console.log('   You can now use the application with file uploads.');
    console.log('');
    
  } catch (error) {
    console.error('\n❌ Upload failed!');
    console.error('   Error:', error.message);
    console.log('\n🔧 Troubleshooting steps:');
    console.log('1. Verify your access token has these permissions:');
    console.log('   - files.content.write');
    console.log('   - files.content.read');
    console.log('   - sharing.write');
    console.log('   - sharing.read');
    console.log('2. Check if your Dropbox has available storage space');
    console.log('3. Verify the token hasn\'t been revoked or expired');
    console.log('4. Try generating a new access token from Dropbox App Console');
    console.log('');
    process.exit(1);
  }
}

// Run the test
testDropboxConnection().catch(error => {
  console.error('❌ Unexpected error:', error);
  process.exit(1);
});
