import fetch from 'node-fetch';

// ⚠️ REPLACE THESE WITH YOUR ACTUAL VALUES ⚠️
const APP_KEY = 'gzauilcz7oz4lrj';
const APP_SECRET = 'shoqzzuqy96tpo8';
const AUTHORIZATION_CODE = '_o_DTMPeWvUAAAAAAAAAXdWRam1Ph-aBJ0aYbgDJb_I';

async function getDropboxTokens() {
  console.log('🔄 Exchanging authorization code for tokens...\n');
  
  // Validate inputs
  if (APP_KEY === 'YOUR_APP_KEY_HERE') {
    console.error('❌ Please replace YOUR_APP_KEY_HERE with your actual App Key');
    console.log('\nSteps:');
    console.log('1. Go to https://www.dropbox.com/developers/apps');
    console.log('2. Select your app');
    console.log('3. Go to Settings tab');
    console.log('4. Copy the "App key" value');
    console.log('5. Replace YOUR_APP_KEY_HERE in this script\n');
    process.exit(1);
  }
  
  if (APP_SECRET === 'YOUR_APP_SECRET_HERE') {
    console.error('❌ Please replace YOUR_APP_SECRET_HERE with your actual App Secret');
    console.log('\nSteps:');
    console.log('1. Go to https://www.dropbox.com/developers/apps');
    console.log('2. Select your app');
    console.log('3. Go to Settings tab');
    console.log('4. Click "Show" next to "App secret"');
    console.log('5. Copy the secret value');
    console.log('6. Replace YOUR_APP_SECRET_HERE in this script\n');
    process.exit(1);
  }
  
  if (AUTHORIZATION_CODE === 'YOUR_AUTHORIZATION_CODE_HERE') {
    console.error('❌ Please replace YOUR_AUTHORIZATION_CODE_HERE with your authorization code');
    console.log('\nSteps:');
    console.log('1. Open this URL in your browser:');
    console.log(`   https://www.dropbox.com/oauth2/authorize?client_id=${APP_KEY}&response_type=code&token_access_type=offline`);
    console.log('2. Click "Allow"');
    console.log('3. Copy the code from the redirected URL (after code=)');
    console.log('4. Replace YOUR_AUTHORIZATION_CODE_HERE in this script\n');
    process.exit(1);
  }

  try {
    const params = new URLSearchParams();
    params.append('code', AUTHORIZATION_CODE);
    params.append('grant_type', 'authorization_code');
    params.append('client_id', APP_KEY);
    params.append('client_secret', APP_SECRET);

    console.log('📡 Sending request to Dropbox API...');
    
    const response = await fetch('https://api.dropbox.com/oauth2/token', {
      method: 'POST',
      body: params.toString(),
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    });

    const data = await response.json();
    
    if (response.ok) {
      console.log('\n✅ SUCCESS! Tokens received.\n');
      console.log('═══════════════════════════════════════════════════════');
      console.log('📋 YOUR DROPBOX CREDENTIALS');
      console.log('═══════════════════════════════════════════════════════\n');
      
      console.log('Access Token (temporary, 4 hours):');
      console.log(data.access_token);
      console.log('');
      
      console.log('🔑 Refresh Token (IMPORTANT - NEVER EXPIRES):');
      console.log(data.refresh_token);
      console.log('');
      
      console.log('Token Type:', data.token_type);
      console.log('Expires In:', data.expires_in, 'seconds (4 hours)');
      console.log('Scope:', data.scope || 'All scopes');
      console.log('Account ID:', data.account_id);
      console.log('');
      
      console.log('═══════════════════════════════════════════════════════');
      console.log('📝 ADD THESE TO YOUR .env FILE:');
      console.log('═══════════════════════════════════════════════════════\n');
      
      console.log('# Dropbox OAuth2 Configuration');
      console.log(`DROPBOX_APP_KEY=${APP_KEY}`);
      console.log(`DROPBOX_APP_SECRET=${APP_SECRET}`);
      console.log(`DROPBOX_REFRESH_TOKEN=${data.refresh_token}`);
      console.log('');
      
      console.log('═══════════════════════════════════════════════════════\n');
      
      console.log('✅ Next Steps:');
      console.log('1. Copy the three lines above');
      console.log('2. Open Backend/.env file');
      console.log('3. Paste the lines (replace old DROPBOX_ACCESS_TOKEN if present)');
      console.log('4. Save the .env file');
      console.log('5. Restart your server');
      console.log('6. Run: node test-dropbox-connection.js');
      console.log('');
      
      console.log('⚠️  IMPORTANT:');
      console.log('- Keep the REFRESH TOKEN secure (it never expires!)');
      console.log('- Never commit .env file to Git');
      console.log('- Delete this script after getting your tokens');
      console.log('');
      
    } else {
      console.error('\n❌ ERROR: Failed to get tokens\n');
      console.error('Status:', response.status, response.statusText);
      console.error('Response:', data);
      console.log('');
      
      if (data.error === 'invalid_grant') {
        console.log('💡 Common Causes:');
        console.log('- Authorization code already used (can only be used once)');
        console.log('- Authorization code expired (valid for 10 minutes)');
        console.log('- Wrong authorization code');
        console.log('');
        console.log('🔧 Solution:');
        console.log('1. Generate a NEW authorization code:');
        console.log(`   https://www.dropbox.com/oauth2/authorize?client_id=${APP_KEY}&response_type=code&token_access_type=offline`);
        console.log('2. Update AUTHORIZATION_CODE in this script');
        console.log('3. Run this script again');
      } else if (data.error === 'invalid_client') {
        console.log('💡 Common Causes:');
        console.log('- Wrong App Key (client_id)');
        console.log('- Wrong App Secret (client_secret)');
        console.log('');
        console.log('🔧 Solution:');
        console.log('1. Go to https://www.dropbox.com/developers/apps');
        console.log('2. Select your app → Settings tab');
        console.log('3. Copy the correct App Key and App Secret');
        console.log('4. Update them in this script');
        console.log('5. Run this script again');
      } else {
        console.log('🔧 Troubleshooting:');
        console.log('1. Verify all values are correct');
        console.log('2. Check permissions in Dropbox App Console');
        console.log('3. Make sure redirect URI is set to: http://localhost');
        console.log('4. Try generating a new authorization code');
      }
      console.log('');
    }
  } catch (error) {
    console.error('\n❌ UNEXPECTED ERROR:\n');
    console.error(error.message);
    console.log('');
    console.log('🔧 Troubleshooting:');
    console.log('1. Check your internet connection');
    console.log('2. Verify all credentials are correct');
    console.log('3. Make sure node-fetch is installed: npm install node-fetch@2');
    console.log('');
  }
}

// Run the function
getDropboxTokens();
