/**
 * Google Calendar Configuration Test Script
 *
 * Validates your Google Calendar + Meet integration setup
 * Run: node scripts/test-google-calendar-setup.mjs
 */

import { config } from 'dotenv';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Load environment variables
config({ path: join(__dirname, '../.env.local') });

console.log('🔍 Google Calendar + Meet Integration Test\n');
console.log('=' .repeat(60));

// Check 1: Integration enabled
console.log('\n1️⃣  Checking if integration is enabled...');
const enabled = process.env.ENABLE_GOOGLE_CALENDAR_INTEGRATION === 'true';
if (enabled) {
  console.log('   ✅ ENABLED');
} else {
  console.log('   ⚠️  DISABLED');
  console.log('   💡 Set ENABLE_GOOGLE_CALENDAR_INTEGRATION=true in .env.local');
}

// Check 2: Service account email
console.log('\n2️⃣  Checking service account email...');
const email = process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL;
if (email) {
  console.log(`   ✅ ${email}`);
} else {
  console.log('   ❌ MISSING');
  console.log('   💡 Set GOOGLE_SERVICE_ACCOUNT_EMAIL in .env.local');
}

// Check 3: Service account key
console.log('\n3️⃣  Checking service account key...');
const key = process.env.GOOGLE_SERVICE_ACCOUNT_KEY;
if (key) {
  console.log(`   ✅ Present (${key.length} characters)`);

  // Try to decode and validate
  try {
    const decoded = Buffer.from(key, 'base64').toString('utf-8');
    const keyJson = JSON.parse(decoded);

    if (keyJson.type === 'service_account') {
      console.log('   ✅ Valid service account key');
      console.log(`   📧 Key email: ${keyJson.client_email}`);
      console.log(`   🆔 Project ID: ${keyJson.project_id}`);
    } else {
      console.log('   ⚠️  Not a service account key');
    }
  } catch (error) {
    console.log('   ❌ Invalid base64 or JSON format');
    console.log(`   💡 Error: ${error.message}`);
  }
} else {
  console.log('   ❌ MISSING');
  console.log('   💡 Set GOOGLE_SERVICE_ACCOUNT_KEY in .env.local');
  console.log('   💡 Encode with: cat key.json | base64 | tr -d \'\\n\'');
}

// Check 4: Calendar ID
console.log('\n4️⃣  Checking calendar ID...');
const calendarId = process.env.GOOGLE_CALENDAR_ID;
if (calendarId) {
  console.log(`   ✅ ${calendarId}`);

  if (calendarId === 'primary') {
    console.log('   ⚠️  Using primary calendar (not recommended)');
    console.log('   💡 Create a dedicated calendar for demo bookings');
  }
} else {
  console.log('   ❌ MISSING');
  console.log('   💡 Set GOOGLE_CALENDAR_ID in .env.local');
}

// Check 5: Optional impersonation
console.log('\n5️⃣  Checking impersonation settings...');
const impersonatedUser = process.env.GOOGLE_CALENDAR_IMPERSONATED_USER;
if (impersonatedUser) {
  console.log(`   ℹ️  Impersonating: ${impersonatedUser}`);
  console.log('   ℹ️  Ensure domain-wide delegation is configured');
} else {
  console.log('   ℹ️  No impersonation (standard service account)');
}

// Summary
console.log('\n' + '='.repeat(60));
console.log('\n📊 Summary:\n');

const checks = [
  { name: 'Integration enabled', pass: enabled },
  { name: 'Service account email', pass: !!email },
  { name: 'Service account key', pass: !!key },
  { name: 'Calendar ID', pass: !!calendarId },
];

const passed = checks.filter((c) => c.pass).length;
const total = checks.length;

checks.forEach((check) => {
  console.log(`   ${check.pass ? '✅' : '❌'} ${check.name}`);
});

console.log(`\n   Score: ${passed}/${total} checks passed\n`);

if (passed === total && enabled) {
  console.log('🎉 Configuration looks good!');
  console.log('\n📝 Next Steps:');
  console.log('   1. Restart your dev server: npm run dev');
  console.log('   2. Book a test demo: http://localhost:9000/en/demo');
  console.log('   3. Check your email for Meet link');
  console.log('   4. Check Google Calendar for event');
  console.log('\n📚 Full guide: GOOGLE_CALENDAR_MEET_SETUP.md');
} else if (passed === total && !enabled) {
  console.log('⚠️  Configuration is valid but integration is DISABLED');
  console.log('\n💡 To enable:');
  console.log('   Set ENABLE_GOOGLE_CALENDAR_INTEGRATION=true in .env.local');
} else {
  console.log('⚠️  Configuration incomplete');
  console.log('\n💡 Fix missing items above, then run this script again');
  console.log('📚 Full setup guide: GOOGLE_CALENDAR_MEET_SETUP.md');
}

console.log('\n' + '='.repeat(60) + '\n');

// Exit with appropriate code
process.exit(passed === total ? 0 : 1);
