const { createDAVClient } = require('tsdav');
const fs = require('fs');
const path = require('path');

function loadEnv() {
  const envPath = path.join(__dirname, '.env');
  const envContent = fs.readFileSync(envPath, 'utf-8');
  const env = {};
  
  envContent.split('\n').forEach(line => {
    const match = line.match(/^([^=:#]+)=(.*)$/);
    if (match) {
      const key = match[1].trim();
      let value = match[2].trim();
      
      if (value.startsWith('"') && value.endsWith('"')) {
        value = value.slice(1, -1);
        value = value.replace(/\\"/g, '"');
        value = value.replace(/\\\\/g, '\\');
      } else if (value.startsWith("'") && value.endsWith("'")) {
        value = value.slice(1, -1);
      }
      
      env[key] = value;
    }
  });
  
  return env;
}

async function testNextcloudConnection() {
  console.log('🔍 Testing Nextcloud CalDAV connection...\n');
  
  const env = loadEnv();
  const serverUrl = env.NEXTCLOUD_URL;
  const username = env.NEXTCLOUD_USERNAME;
  const password = env.NEXTCLOUD_PASSWORD;

  console.log('Configuration:');
  console.log('  Server URL:', serverUrl);
  console.log('  Username:', username);
  console.log('  Password:', password ? '***' + password.slice(-3) : 'NOT SET');
  console.log('  CalDAV URL:', `${serverUrl}/remote.php/dav`);
  console.log('');

  if (!serverUrl || !username || !password) {
    console.error('❌ Missing Nextcloud credentials in .env file!');
    process.exit(1);
  }

  try {
    console.log('⏳ Connecting to Nextcloud...');
    
    const client = await createDAVClient({
      serverUrl: `${serverUrl}/remote.php/dav`,
      credentials: {
        username,
        password,
      },
      authMethod: 'Basic',
      defaultAccountType: 'caldav',
    });

    console.log('✅ Successfully connected to Nextcloud!\n');

    console.log('📅 Fetching calendars...');
    const calendars = await client.fetchCalendars();

    if (calendars.length === 0) {
      console.log('⚠️  No calendars found.');
    } else {
      console.log(`✅ Found ${calendars.length} calendar(s):\n`);
      calendars.forEach((cal, idx) => {
        console.log(`  ${idx + 1}. ${cal.displayName}`);
        console.log(`     URL: ${cal.url}`);
        if (cal.description) {
          console.log(`     Description: ${cal.description}`);
        }
        console.log('');
      });
    }

    console.log('🎉 Nextcloud connection test successful!');
    process.exit(0);

  } catch (error) {
    console.error('\n❌ Connection failed!');
    console.error('Error:', error.message);
    
    if (error.response) {
      console.error('Status:', error.response.status, error.response.statusText);
    }
    
    console.error('\n💡 Troubleshooting:');
    console.error('  1. Check if the Nextcloud URL is correct');
    console.error('  2. Verify username and password');
    console.error('  3. Make sure CalDAV is enabled in Nextcloud');
    console.error('  4. Check if the user has calendar access');
    
    process.exit(1);
  }
}

testNextcloudConnection();
