#!/usr/bin/env node

/**
 * QuickBooks Token Status Checker
 * Diagnostic tool to check token persistence and connection status
 */

const fs = require('fs');
const path = require('path');

const TOKENS_FILE = path.join(__dirname, '.tokens.json');

console.log('🔍 QuickBooks Token Status Checker');
console.log('===================================\n');

// Check if tokens file exists
if (!fs.existsSync(TOKENS_FILE)) {
    console.log('❌ TOKENS FILE NOT FOUND');
    console.log(`   File: ${TOKENS_FILE}`);
    console.log('   This means your QuickBooks connection will be lost on server restart!');
    console.log('\n💡 SOLUTION:');
    console.log('   1. Go to your admin dashboard: http://localhost:3000/admin/login');
    console.log('   2. Click "Connect QuickBooks"');
    console.log('   3. Complete the OAuth flow');
    console.log('   4. The tokens will be saved automatically');
    process.exit(1);
}

// Load and analyze tokens
try {
    const data = JSON.parse(fs.readFileSync(TOKENS_FILE, 'utf8'));
    const now = Date.now();
    
    console.log('✅ TOKENS FILE FOUND');
    console.log(`   File: ${TOKENS_FILE}`);
    console.log(`   Size: ${fs.statSync(TOKENS_FILE).size} bytes`);
    console.log(`   Last modified: ${new Date(fs.statSync(TOKENS_FILE).mtime).toLocaleString()}\n`);
    
    // Check token components
    console.log('🔑 TOKEN COMPONENTS:');
    console.log(`   Access Token: ${data.accessToken ? '✅ Present' : '❌ Missing'}`);
    console.log(`   Refresh Token: ${data.refreshToken ? '✅ Present' : '❌ Missing'}`);
    console.log(`   Realm ID: ${data.realmId ? `✅ ${data.realmId}` : '❌ Missing'}`);
    
    if (data.tokenExpiresAt) {
        const expiresAt = new Date(data.tokenExpiresAt);
        const timeUntilExpiry = data.tokenExpiresAt - now;
        const hoursUntilExpiry = Math.floor(timeUntilExpiry / (1000 * 60 * 60));
        const minutesUntilExpiry = Math.floor((timeUntilExpiry % (1000 * 60 * 60)) / (1000 * 60));
        
        console.log(`   Expires At: ${expiresAt.toLocaleString()}`);
        console.log(`   Time Until Expiry: ${hoursUntilExpiry}h ${minutesUntilExpiry}m`);
        
        if (timeUntilExpiry <= 0) {
            console.log('   ⚠️  TOKEN IS EXPIRED!');
        } else if (timeUntilExpiry < 600000) { // Less than 10 minutes
            console.log('   ⚠️  TOKEN EXPIRES SOON!');
        } else {
            console.log('   ✅ Token is valid');
        }
    } else {
        console.log('   ❌ No expiration time found');
    }
    
    console.log('\n📊 CONNECTION STATUS:');
    if (data.accessToken && data.refreshToken && data.realmId) {
        if (data.tokenExpiresAt && data.tokenExpiresAt > now) {
            console.log('   ✅ FULLY CONNECTED - Ready for payments');
        } else if (data.refreshToken) {
            console.log('   🔄 EXPIRED BUT REFRESHABLE - Will auto-refresh on next API call');
        } else {
            console.log('   ❌ EXPIRED AND NO REFRESH - Reconnection required');
        }
    } else {
        console.log('   ❌ INCOMPLETE CONNECTION - Missing required tokens');
    }
    
    console.log('\n💡 RECOMMENDATIONS:');
    if (!data.accessToken || !data.refreshToken || !data.realmId) {
        console.log('   • Reconnect to QuickBooks via admin dashboard');
    } else if (data.tokenExpiresAt && data.tokenExpiresAt <= now) {
        console.log('   • Token is expired but refreshable - make an API call to trigger refresh');
    } else {
        console.log('   • Connection is healthy - no action needed');
    }
    
} catch (error) {
    console.log('❌ ERROR READING TOKENS FILE:');
    console.log(`   ${error.message}`);
    console.log('\n💡 SOLUTION:');
    console.log('   • Delete the corrupted .tokens.json file');
    console.log('   • Reconnect to QuickBooks via admin dashboard');
}
