#!/usr/bin/env node

/**
 * Sync Schema Cache
 * Synchronizes the local schema cache with the Directus instance
 */

const { getAuthenticatedClient } = require('./directus-client');
const { getCache } = require('./schema-cache');

async function syncCache() {
  console.log('🔄 Starting schema cache synchronization...\n');
  
  try {
    // Get authenticated client
    const client = await getAuthenticatedClient();
    
    // Get cache instance
    const cache = getCache();
    await cache.init();
    
    // Get current stats before sync
    const statsBefore = cache.getStats();
    console.log('📊 Cache stats before sync:');
    console.log(`  Collections: ${statsBefore.customCollections}`);
    console.log(`  Fields: ${statsBefore.totalFields}`);
    console.log(`  Relations: ${statsBefore.totalRelations}`);
    console.log(`  Last sync: ${statsBefore.lastSync || 'Never'}\n`);
    
    // Perform sync
    await cache.sync(client);
    
    // Get stats after sync
    const statsAfter = cache.getStats();
    console.log('\n📊 Cache stats after sync:');
    console.log(`  Collections: ${statsAfter.customCollections}`);
    console.log(`  Fields: ${statsAfter.totalFields}`);
    console.log(`  Relations: ${statsAfter.totalRelations}`);
    console.log(`  Cache file: ${statsAfter.cacheFile}`);
    
    console.log('\n✅ Cache synchronization complete!');
    
  } catch (error) {
    console.error('❌ Failed to sync cache:', error.message);
    process.exit(1);
  }
}

// Run if called directly
if (require.main === module) {
  syncCache();
}

module.exports = { syncCache };