<?php

namespace App\Console\Commands;

use App\Models\Committee;
use App\Models\WorkGroup;
use App\Models\User;
use App\Models\Contact;
use App\Models\ContactFolder;
use App\Models\MicrosoftUser;
use App\Services\MicrosoftGraphSyncService;
use App\Services\MicrosoftGraph\MicrosoftGraphApiClient;
use App\Services\MicrosoftGraph\MicrosoftGraphContactService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class SyncMicrosoftGraphCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'msgraph:sync
                            {--dry-run : Run sync in dry-run mode without making changes}
                            {--test-connection : Test Microsoft Graph API connection and permissions}
                            {--test-contact-folder= : Create a test contact folder with the given name (default: Test-Folder)}
                            {--contact-folders : Sync only contact folders}
                            {--contacts : Sync only contacts}
                            {--cleanup-database : Clean up ALL ms_id values from database (committees, workgroups)}
                            {--confirm-deletion : Required confirmation flag for deletion operations}
                            {--list-folders : List all contact folders from Microsoft Graph}
                            {--with-contact-count : Include contact count when listing folders (slower)}
                            {--list-contacts= : List contacts from a specific folder (provide folder ID or name)}
                            {--list-all-contacts : List all contacts from all folders}
                            {--sync-folder-ids : Sync existing Microsoft Graph folder IDs with database}
                            {--clear-contacts : Clear all contacts from existing folders (without deleting folders)}
                            {--delete-folders : Delete ALL contact folders from Microsoft Graph (DESTRUCTIVE)}
                            {--delete-everything : Delete ALL contact folders and contacts from Microsoft Graph AND clean local database (ULTRA DESTRUCTIVE)}
                            {--all : Run complete clean slate synchronization (default behavior)}
                            {--get-user= : Fetch a user from Microsoft Graph by email or ID and display the response}
                            {--get-contact= : Fetch a specific contact from Microsoft Graph by contact ID and display the response}
                            {--sync-specific-contact= : Sync a specific contact by user_id and folder_id (format: user_id,folder_id)}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Microsoft Graph synchronization: Process new users only (is_new=1) with permanent folder deletion and recreation. Use --sync-specific-contact=user_id,folder_id to retry failed contacts. Use --get-contact=contact_id to fetch a specific contact by Microsoft Graph ID.';

    protected $syncService;

    public function __construct(MicrosoftGraphSyncService $syncService)
    {
        parent::__construct();
        $this->syncService = $syncService;
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('🚀 Starting Microsoft Graph Clean Slate synchronization...');

        // Initialize the service - this will check if MS Graph is available
        if (!MicrosoftGraphSyncService::isAvailable()) {
            $this->error('❌ Microsoft Graph is not available. Please run migrations first.');
            return Command::FAILURE;
        }
        $this->syncService->initialize();

        // Test connection if requested
        if ($this->option('test-connection')) {
            return $this->testConnection();
        }

        // Test contact folder creation if requested
        if ($this->option('test-contact-folder') !== null) {
            return $this->testContactFolder();
        }

        // List operations
        if ($this->option('list-folders')) {
            return $this->listContactFolders();
        }

        if ($this->option('list-contacts') !== null) {
            return $this->listContacts($this->option('list-contacts'));
        }

        if ($this->option('list-all-contacts')) {
            return $this->listAllContacts();
        }

        // Get user from Microsoft Graph
        if ($this->option('get-user') !== null) {
            return $this->getUserFromGraph($this->option('get-user'));
        }

        // Get contact from Microsoft Graph
        if ($this->option('get-contact') !== null) {
            return $this->getContactFromGraph($this->option('get-contact'));
        }

        // Sync specific contact
        if ($this->option('sync-specific-contact') !== null) {
            return $this->syncSpecificContact($this->option('sync-specific-contact'));
        }

        // Nuevas operaciones del enfoque actualizado
        if ($this->option('sync-folder-ids')) {
            return $this->syncFolderIds();
        }

        if ($this->option('clear-contacts')) {
            return $this->clearContacts();
        }

        if ($this->option('delete-folders')) {
            return $this->deleteAllContactFolders();
        }

        if ($this->option('delete-everything')) {
            return $this->deleteEverything();
        }

        // Database cleanup operation
        if ($this->option('cleanup-database')) {
            return $this->cleanupDatabase();
        }

        if ($this->option('dry-run')) {
            $this->warn('⚠️  Running in DRY-RUN mode - no changes will be made');
        }

        $startTime = microtime(true);

        try {
            $results = [];

            // Determine what to sync based on options
            if ($this->option('contact-folders')) {
                $this->info('📁 Recreating contact folders only...');
                $results['contact_folders'] = $this->syncService->syncContactFolders($this->option('dry-run'));
                $this->displayContactFolderResults($results['contact_folders']);
            } elseif ($this->option('contacts')) {
                $this->info('📧 Syncing contacts only...');
                $results['contacts'] = $this->syncService->syncContacts($this->option('dry-run'));
                $this->displayContactResults($results['contacts']);
            } else {
                // Default: Process new users only
                $this->info('🔄 Running NEW USERS synchronization (permanent folder deletion for is_new=1 users)...');
                $results = $this->syncService->syncAll($this->option('dry-run'));
                $this->displayCleanSlateResults($results);
            }

            $executionTime = round(microtime(true) - $startTime, 2);
            $this->info("✅ Clean Slate synchronization completed in {$executionTime} seconds");

            // Log the results
            Log::info('Microsoft Graph Clean Slate sync completed via artisan command', [
                'execution_time' => $executionTime,
                'results' => $results,
                'dry_run' => $this->option('dry-run')
            ]);

            return Command::SUCCESS;

        } catch (\Exception $e) {
            $this->error('❌ Clean Slate synchronization failed: ' . $e->getMessage());
            Log::error('Microsoft Graph Clean Slate sync failed via artisan command', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return Command::FAILURE;
        }
    }

    /**
     * Test Microsoft Graph API connection and permissions
     *
     * @return int
     */
    protected function testConnection()
    {
        $this->info('🔌 Testing Microsoft Graph API connection...');

        try {
            $results = $this->syncService->testConnection();

            if (isset($results['error'])) {
                $this->error('❌ Connection test failed: ' . $results['error']);
                return Command::FAILURE;
            }

            $this->info('✅ Connection test successful!');

            // Display tenant information
            if (isset($results['tenant'])) {
                $this->info('🏢 Tenant Information:');
                $this->table(['Property', 'Value'], [
                    ['Tenant ID', $results['tenant']['id'] ?? 'N/A'],
                    ['Display Name', $results['tenant']['displayName'] ?? 'N/A'],
                    ['Domain', $results['tenant']['verifiedDomains'][0]['name'] ?? 'N/A']
                ]);
            }

            // Display permissions test results
            if (isset($results['permissions']) && !empty($results['permissions'])) {
                $this->info('🔐 Permission Tests:');
                foreach ($results['permissions'] as $permission) {
                    $this->line($permission);
                }
            }

            $this->info('🚀 Microsoft Graph API is ready for synchronization!');
            return Command::SUCCESS;

        } catch (\Exception $e) {
            $this->error('❌ Connection test failed: ' . $e->getMessage());
            Log::error('Microsoft Graph connection test failed via artisan command', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return Command::FAILURE;
        }
    }

    protected function displayContactFolderResults(array $results)
    {
        $this->table(['Metric', 'Count'], [
            ['📁 Created', $results['created']],
            ['📝 Updated', $results['updated']],
            ['❌ Errors', $results['errors']]
        ]);

        // Show additional details if available
        if (isset($results['service_users_processed'])) {
            $this->line('');
            $this->info("👥 Service Users Processed: {$results['service_users_processed']}");
        }

        if (isset($results['committees_processed']) && isset($results['workgroups_processed'])) {
            $this->info("🏛️ Committees Processed: {$results['committees_processed']}");
            $this->info("👨‍💼 Workgroups Processed: {$results['workgroups_processed']}");
        }
    }

    protected function displayContactResults(array $results)
    {
        $this->table(['Metric', 'Count'], [
            ['📧 Created', $results['created']],
            ['📝 Updated', $results['updated']],
            ['🗑️ Removed', $results['removed']],
            ['❌ Errors', $results['errors']]
        ]);
    }

    protected function displayCleanSlateResults(array $results)
    {
        $this->info('📊 Microsoft Graph Synchronization Results (New Users Only):');

        // Check if we have new format (new users sync) or old format
        if (isset($results['new_users_found'])) {
            // New format: users-based sync
            $this->info('👥 Step 1 - New Users Processing:');
            $this->table(['Metric', 'Count'], [
                ['New Users Found', $results['new_users_found']],
                ['Users Processed', $results['users_processed'] ?? 0]
            ]);

            if ($results['new_users_found'] > 0) {
                $this->info('🗑️ Step 2 - Folder Deletion:');
                $this->table(['Metric', 'Count'], [
                    ['Folders Deleted', $results['folders_deleted'] ?? 0]
                ]);

                $this->info('📁 Step 3 - Folder Recreation:');
                $this->table(['Metric', 'Count'], [
                    ['Folders Created/Updated', $results['folders_created'] ?? 0]
                ]);

                $this->info('📧 Step 4 - Contact Creation:');
                $this->table(['Metric', 'Count'], [
                    ['Contacts Created', $results['contacts_created'] ?? 0]
                ]);

                $this->info('✅ Step 5 - User Status Update:');
                $this->table(['Metric', 'Count'], [
                    ['Users Marked as Processed', $results['users_updated'] ?? 0]
                ]);
            }

            // Summary
            $this->info('📈 Summary:');
            $this->table(['Metric', 'Total'], [
                ['New Users Processed', $results['users_processed'] ?? 0],
                ['Total Folders Deleted', $results['folders_deleted'] ?? 0],
                ['Total Folders Created', $results['folders_created'] ?? 0],
                ['Total Contacts Created', $results['contacts_created'] ?? 0],
                ['Total Errors', count($results['errors'] ?? [])]
            ]);

        } else {
            // Legacy format: keep backward compatibility
            // Step 1: Contact folders synchronization
            if (isset($results['folders'])) {
                $this->info('📁 Step 1 - Contact Folders Sync:');
                $this->displayContactFolderResults($results['folders']);
            }

            // Step 2: Contact clearing
            if (isset($results['contacts_cleared'])) {
                $this->info('🧹 Step 2 - Contact Clearing:');
                $this->table(['Metric', 'Count'], [
                    ['Contacts Deleted', $results['contacts_cleared']['contacts_deleted'] ?? 0],
                    ['Errors', count($results['contacts_cleared']['errors'] ?? [])]
                ]);
            }

            // Step 3: Contacts recreation
            if (isset($results['contacts'])) {
                $this->info('📧 Step 3 - Contacts Recreation:');
                $this->displayContactResults($results['contacts']);
            }

            // Summary totals
            $totalFoldersCreated = ($results['folders']['created'] ?? 0) + ($results['folders']['updated'] ?? 0);
            $totalCleared = $results['contacts_cleared']['contacts_deleted'] ?? 0;
            $totalContactsCreated = ($results['contacts']['created'] ?? 0);
            $totalErrors = count($results['errors'] ?? []);

            $this->info('📈 Clean Slate Summary:');
            $this->table(['Metric', 'Total'], [
                ['Total Folders Created/Updated', $totalFoldersCreated],
                ['Total Contacts Cleared', $totalCleared],
                ['Total Contacts Created', $totalContactsCreated],
                ['Total Errors', $totalErrors]
            ]);
        }

        if ($results['success'] ?? false) {
            if (isset($results['new_users_found'])) {
                $this->info('✅ New users synchronization completed successfully');
                if (($results['new_users_found'] ?? 0) === 0) {
                    $this->info('ℹ️  No new users found to process (all users already processed)');
                } else {
                    $this->info("🔄 {$results['users_updated']} users marked as processed (is_new = 0)");
                }
            } else {
                $this->info('✅ Clean Slate synchronization completed successfully');
            }
        } else {
            $this->warn('⚠️  Synchronization completed with errors');
            if (!empty($results['errors'])) {
                $this->error('Error details:');
                foreach ($results['errors'] as $error) {
                    $this->error('- ' . $error);
                }
            }
        }
    }

    protected function displayAllResults(array $results)
    {
        $this->info('📊 Contact Synchronization Results:');

        $this->info('📁 Contact Folders:');
        $this->displayContactFolderResults($results['contact_folders']);

        // Show orphaned cleanup results if they exist
        if (isset($results['orphaned_cleanup'])) {
            $this->info('🧹 Orphaned Cleanup:');
            $this->table(['Metric', 'Count'], [
                ['Folders Deleted', $results['orphaned_cleanup']['deleted']],
                ['Errors', $results['orphaned_cleanup']['errors']]
            ]);
        }

        $this->info('📧 Contacts:');
        $this->displayContactResults($results['contacts']);

        // Summary totals
        $totalCreated = $results['contact_folders']['created'] + $results['contacts']['created'];
        $totalUpdated = $results['contact_folders']['updated'] + $results['contacts']['updated'];
        $totalRemoved = ($results['contacts']['removed'] ?? 0) + (isset($results['orphaned_cleanup']) ? $results['orphaned_cleanup']['deleted'] : 0);
        $totalErrors = $results['contact_folders']['errors'] + $results['contacts']['errors'] + (isset($results['orphaned_cleanup']) ? $results['orphaned_cleanup']['errors'] : 0);

        $this->info('📈 Summary:');
        $this->table(['Metric', 'Total'], [
            ['Total Created', $totalCreated],
            ['Total Updated', $totalUpdated],
            ['Total Removed', $totalRemoved],
            ['Total Errors', $totalErrors]
        ]);
    }

    /**
     * Test creating a contact folder
     *
     * @return int
     */
    protected function testContactFolder()
    {
        $folderName = $this->option('test-contact-folder') ?: 'Test-Folder';

        $this->info("🧪 Testing contact folder creation...");
        $this->info("📁 Folder name: {$folderName}");

        try {
            // Create the test contact folder
            $this->info("📝 Creating contact folder '{$folderName}'...");
            $createResults = $this->syncService->createTestContactFolder($folderName);

            if ($createResults['success']) {
                $this->info("✅ Contact folder '{$folderName}' created successfully!");
                $this->table(['Property', 'Value'], [
                    ['Folder Name', $createResults['folder_name']],
                    ['Folder ID', $createResults['folder_id']],
                    ['Service User Email', $createResults['service_user_email']],
                    ['Service User ID', $createResults['service_user_id']]
                ]);

                // Display service users test results
                if (isset($createResults['service_users_tested']) && !empty($createResults['service_users_tested'])) {
                    $this->line('');
                    $this->info("👥 Service Users Connection Test:");

                    $userTableData = [];
                    foreach ($createResults['service_users_tested'] as $userTest) {
                        $userTableData[] = [
                            'Name' => $userTest['name'] ?? 'N/A',
                            'Email' => $userTest['email'],
                            'Status' => $userTest['status'] === 'success' ? '✅ Connected' : '❌ Error',
                            'Folders' => $userTest['folder_count'] ?? $userTest['error'] ?? 'N/A'
                        ];
                    }

                    $this->table(['Name', 'Email', 'Status', 'Folders/Error'], $userTableData);
                }

                // Ask if user wants to delete the test folder
                if ($this->confirm("🗑️  Do you want to delete the test contact folder '{$folderName}'?", true)) {
                    $this->info("🗑️  Deleting test contact folder...");
                    $deleteResults = $this->syncService->deleteTestContactFolder($createResults['folder_id']);

                    if ($deleteResults['success']) {
                        $this->info("✅ Test contact folder deleted successfully!");
                    } else {
                        $this->error("❌ Failed to delete test contact folder: " . $deleteResults['error']);
                        $this->warn("⚠️  You may need to manually delete the folder with ID: " . $createResults['folder_id']);
                    }
                } else {
                    $this->warn("⚠️  Test contact folder left in place with ID: " . $createResults['folder_id']);
                    $this->info("💡 You can delete it later using the Microsoft Graph API or via Outlook");
                }

                return Command::SUCCESS;
            } else {
                $this->error("❌ Failed to create contact folder: " . $createResults['error']);

                // Show troubleshooting information
                $this->warn("🔍 Troubleshooting information:");
                $this->table(['Property', 'Value'], [
                    ['Service User Email', $createResults['service_user_email'] ?? 'Not configured'],
                    ['Service User ID', $createResults['service_user_id'] ?? 'Not configured'],
                    ['Error', $createResults['error'] ?? 'Unknown']
                ]);

                // Show service users test results if available
                if (isset($createResults['service_users_tested']) && !empty($createResults['service_users_tested'])) {
                    $this->line('');
                    $this->warn("👥 Service Users Status:");

                    $userTableData = [];
                    foreach ($createResults['service_users_tested'] as $userTest) {
                        $userTableData[] = [
                            'Email' => $userTest['email'],
                            'Status' => $userTest['status'] === 'success' ? '✅ OK' : '❌ Error',
                            'Details' => $userTest['folder_count'] ?? $userTest['error'] ?? 'N/A'
                        ];
                    }

                    $this->table(['Email', 'Status', 'Details'], $userTableData);
                }

                $this->warn("💡 Make sure:");
                $this->warn("   - Service users are configured in the database");
                $this->warn("   - Service users exist in your tenant");
                $this->warn("   - Application has Contacts.ReadWrite permissions");

                return Command::FAILURE;
            }

        } catch (\Exception $e) {
            $this->error('❌ Contact folder test failed: ' . $e->getMessage());
            return Command::FAILURE;
        }
    }

    /**
     * Clean up database ms_id values
     */
    protected function cleanupDatabase(): int
    {
        $dryRun = $this->option('dry-run');

        $this->info(" " . ($dryRun ? 'DRY-RUN: ' : '') . "Cleaning up ALL ms_id values from database...");
        $this->warn("⚠️  This will remove ms_id from all committees and workgroups");

        if (!$dryRun && !$this->confirm('Are you sure you want to clean up ALL ms_id values from the database?')) {
            $this->info('❌ Operation cancelled');
            return Command::FAILURE;
        }

        try {
            $startTime = microtime(true);

            $committeesCount = 0;
            $workgroupsCount = 0;

            if ($dryRun) {
                // Count what would be cleared
                $committeesCount = Committee::whereNotNull('ms_id')->count();
                $workgroupsCount = WorkGroup::whereNotNull('ms_id')->count();
                $this->info("🧪 MOCK: Would clear ms_id from {$committeesCount} committees and {$workgroupsCount} workgroups");
            } else {
                // Actually clear the ms_id values
                $committeesCount = Committee::whereNotNull('ms_id')->update(['ms_id' => null]);
                $workgroupsCount = WorkGroup::whereNotNull('ms_id')->update(['ms_id' => null]);
                Log::info("🧹 Cleared ms_id from {$committeesCount} committees and {$workgroupsCount} workgroups");
            }

            $executionTime = round(microtime(true) - $startTime, 2);

            // Display results
            $this->newLine();
            $this->info('📊 Database Cleanup Results:');
            $this->table(
                ['Entity Type', 'Records Updated'],
                [
                    ['Committees', $committeesCount],
                    ['Workgroups', $workgroupsCount]
                ]
            );

            $this->newLine();
            if ($dryRun) {
                $this->info("🧪 DRY-RUN completed in {$executionTime} seconds");
                $this->info("💡 Run without --dry-run to actually clean up the database");
            } else {
                $this->info("✅ Database cleanup completed in {$executionTime} seconds");
            }

            return Command::SUCCESS;

        } catch (\Exception $e) {
            $this->error('❌ Error cleaning up database: ' . $e->getMessage());
            Log::error('Error cleaning up database ms_id values', [
                'error' => $e->getMessage()
            ]);
            return Command::FAILURE;
        }
    }

    /**
     * List all contact folders from Microsoft Graph
     *
     * @return int
     */
    protected function listContactFolders()
    {
        $withContactCount = $this->option('with-contact-count');
        $this->info('📁 Listing all contact folders from Microsoft Graph...');

        if ($withContactCount) {
            $this->warn('⏳ Fetching contact counts for each folder (this may take a while)...');
        }

        try {
            $response = $this->syncService->listContactFolders(null, $withContactCount);

            // Check if response has errors
            if (isset($response['errors']) && !empty($response['errors'])) {
                $this->warn('⚠️ Some errors occurred while listing folders:');
                foreach ($response['errors'] as $error) {
                    $this->error("  - {$error}");
                }
                $this->line('');
            }

            // Display summary
            $totalUsers = $response['total_users'] ?? 0;
            $totalFolders = $response['total_folders'] ?? 0;
            $this->info("📊 Summary: {$totalFolders} folders across {$totalUsers} service users");
            $this->line('');

            // Display folders grouped by user if available
            if (isset($response['folders_by_user']) && !empty($response['folders_by_user'])) {
                foreach ($response['folders_by_user'] as $userFolder) {
                    $user = $userFolder['user'];
                    $folders = $userFolder['folders'] ?? [];
                    $folderCount = $userFolder['folder_count'] ?? 0;

                    // Display user header
                    $this->info("👤 Service User: {$user['name']} ({$user['email']})");
                    $this->info("🆔 Microsoft ID: {$user['ms_id']} | Folders: {$folderCount}");

                    // Check for errors for this user
                    if (isset($userFolder['error'])) {
                        $this->error("   ❌ Error: {$userFolder['error']}");
                        $this->line('');
                        continue;
                    }

                    if (empty($folders)) {
                        $this->warn('   📭 No contact folders found for this user.');
                    } else {
                        // Display folders for this user
                        $tableData = [];
                        foreach ($folders as $folder) {
                            // Handle both array and object responses
                            $folderId = is_object($folder) ? ($folder->id ?? 'N/A') : ($folder['id'] ?? 'N/A');
                            $folderName = is_object($folder) ? ($folder->displayName ?? 'N/A') : ($folder['displayName'] ?? 'N/A');
                            $parentId = is_object($folder) ? ($folder->parentFolderId ?? null) : ($folder['parentFolderId'] ?? null);
                            $childCount = is_object($folder) ? ($folder->childFolderCount ?? '0') : ($folder['childFolderCount'] ?? '0');
                            $contactCount = is_object($folder) ? ($folder->contactCount ?? 0) : ($folder['contactCount'] ?? 0);

                            $tableData[] = [
                                'ID' => substr($folderId, 0, 30) . (strlen($folderId) > 30 ? '...' : ''),
                                'Name' => $folderName,
                                'Parent ID' => $parentId ? substr($parentId, 0, 20) . '...' : 'Root',
                                'Child Count' => $childCount,
                                'Contacts' => $withContactCount ? $contactCount : 'N/A'
                            ];
                        }

                        $this->table(['ID', 'Name', 'Parent ID', 'Children', 'Contacts'], $tableData);
                    }

                    $this->line('');
                }
            } else {
                // Fallback to displaying service users information if available
                if (isset($response['service_users']) && !empty($response['service_users'])) {
                    $this->info('👥 Service Users:');
                    foreach ($response['service_users'] as $serviceUser) {
                        $this->info("  👤 {$serviceUser['name']} ({$serviceUser['email']}) - {$serviceUser['folder_count']} folders");
                    }
                    $this->line('');
                }

                // Extract and display all folders (legacy format)
                $folders = $response['folders'] ?? [];

                if (empty($folders)) {
                    $this->info('📭 No contact folders found.');
                    return Command::SUCCESS;
                }

                $this->info("📂 All Contact Folders:");

                $tableData = [];
                foreach ($folders as $folder) {
                    // Handle both array and object responses
                    $folderId = is_object($folder) ? ($folder->id ?? 'N/A') : ($folder['id'] ?? 'N/A');
                    $folderName = is_object($folder) ? ($folder->displayName ?? 'N/A') : ($folder['displayName'] ?? 'N/A');
                    $parentId = is_object($folder) ? ($folder->parentFolderId ?? null) : ($folder['parentFolderId'] ?? null);
                    $childCount = is_object($folder) ? ($folder->childFolderCount ?? '0') : ($folder['childFolderCount'] ?? '0');
                    $contactCount = is_object($folder) ? ($folder->contactCount ?? 0) : ($folder['contactCount'] ?? 0);

                    $tableData[] = [
                        'ID' => substr($folderId, 0, 30) . (strlen($folderId) > 30 ? '...' : ''),
                        'Name' => $folderName,
                        'Parent ID' => $parentId ? substr($parentId, 0, 20) . '...' : 'Root',
                        'Child Count' => $childCount,
                        'Contacts' => $withContactCount ? $contactCount : 'N/A'
                    ];
                }

                $this->table(['ID', 'Name', 'Parent ID', 'Children', 'Contacts'], $tableData);
            }

            if (!$withContactCount) {
                $this->line('');
                $this->info("💡 Use --with-contact-count to see the number of contacts in each folder");
            }

            return Command::SUCCESS;

        } catch (\Exception $e) {
            $this->error('❌ Error listing contact folders: ' . $e->getMessage());
            Log::error('Error listing contact folders', [
                'error' => $e->getMessage()
            ]);
            return Command::FAILURE;
        }
    }

    /**
     * List contacts from a specific folder
     *
     * @param string $folderIdOrName
     * @return int
     */
    protected function listContacts(string $folderIdOrName)
    {
        $this->info("📧 Listing contacts from folder: {$folderIdOrName}");

        try {
            $contacts = $this->syncService->listContactsInFolder($folderIdOrName);

            if (empty($contacts)) {
                $this->info('📭 No contacts found in this folder.');
                return Command::SUCCESS;
            }

            $this->info("📊 Found {" . count($contacts) . "} contacts:");

            $tableData = [];
            foreach ($contacts as $contact) {
                $tableData[] = [
                    'Name' => $contact['displayName'] ?? 'N/A',
                    'Email' => $contact['emailAddresses'][0]['address'] ?? 'N/A',
                    'Company' => $contact['companyName'] ?? 'N/A',
                    'Job Title' => $contact['jobTitle'] ?? 'N/A'
                ];
            }

            $this->table(['Name', 'Email', 'Company', 'Job Title'], $tableData);

            return Command::SUCCESS;

        } catch (\Exception $e) {
            $this->error('❌ Error listing contacts: ' . $e->getMessage());
            Log::error('Error listing contacts from folder', [
                'folder' => $folderIdOrName,
                'error' => $e->getMessage()
            ]);
            return Command::FAILURE;
        }
    }

    /**
     * List all contacts from all folders
     *
     * @return int
     */
    protected function listAllContacts()
    {
        $this->info('📧 Listing all contacts from all folders...');

        try {
            $response = $this->syncService->listAllContacts();

            // Check if response has error
            if (isset($response['status']) && $response['status'] === 'error') {
                $this->error('❌ ' . ($response['message'] ?? 'Unknown error occurred'));
                return Command::FAILURE;
            }

            // Extract data from new response format
            $allContacts = [];
            if (isset($response['folders'])) {
                foreach ($response['folders'] as $folderData) {
                    $allContacts[$folderData['folder']['name']] = $folderData['contacts'];
                }
            } elseif (is_array($response) && !isset($response['status'])) {
                // Backward compatibility for old format
                $allContacts = $response;
            }

            if (empty($allContacts)) {
                $this->info('📭 No contacts found in any folder.');
                return Command::SUCCESS;
            }

            $totalContacts = 0;
            foreach ($allContacts as $folderName => $contacts) {
                $contactCount = count($contacts);
                $totalContacts += $contactCount;

                $this->info("📁 Folder: {$folderName} ({$contactCount} contacts)");

                if ($contactCount > 0) {
                    $tableData = [];
                    foreach ($contacts as $contact) {
                        $tableData[] = [
                            'Name' => $contact['displayName'] ?? 'N/A',
                            'Email' => $contact['emailAddresses'][0]['address'] ?? 'N/A',
                            'Company' => $contact['companyName'] ?? 'N/A'
                        ];
                    }

                    $this->table(['Name', 'Email', 'Company'], $tableData);
                    $this->newLine();
                }
            }

            $this->info("📊 Total contacts found: {$totalContacts}");

            return Command::SUCCESS;

        } catch (\Exception $e) {
            $this->error('❌ Error listing all contacts: ' . $e->getMessage());
            Log::error('Error listing all contacts', [
                'error' => $e->getMessage()
            ]);
            return Command::FAILURE;
        }
    }

    /**
     * Sync existing folder IDs from Microsoft Graph with database
     *
     * @return int
     */
    protected function syncFolderIds()
    {
        $this->info('🔄 Syncing existing Microsoft Graph folder IDs with database...');

        try {
            $results = $this->syncService->syncExistingFolderIds($this->option('dry-run'));

            $this->info('📊 Folder ID Sync Results:');
            $this->table(['Metric', 'Count'], [
                ['✅ Synced', $results['synced']],
                ['⚠️ Not Found', $results['not_found']],
                ['❌ Errors', $results['errors']]
            ]);

            if ($results['not_found'] > 0) {
                $this->warn("⚠️ {$results['not_found']} folders were not found in Microsoft Graph");
                $this->info("💡 You may need to create missing folders manually or check folder names");
            }

            return Command::SUCCESS;

        } catch (\Exception $e) {
            $this->error('❌ Error syncing folder IDs: ' . $e->getMessage());
            Log::error('Error syncing folder IDs', [
                'error' => $e->getMessage()
            ]);
            return Command::FAILURE;
        }
    }

    /**
     * Clear all contacts from existing folders
     *
     * @return int
     */
    protected function clearContacts()
    {
        $this->info('🧹 Clearing all contacts from existing folders...');

        if (!$this->option('dry-run')) {
            $this->warn('⚠️ This will DELETE ALL CONTACTS from Microsoft Graph folders!');
            if (!$this->confirm('Are you sure you want to continue?')) {
                $this->info('❌ Operation cancelled by user');
                return Command::SUCCESS;
            }
        }

        try {
            $results = $this->syncService->clearAllContacts($this->option('dry-run'));

            $this->info('📊 Contact Clearing Results:');
            $this->table(['Metric', 'Count'], [
                ['📁 Folders Processed', $results['cleared_folders']],
                ['📧 Contacts Removed', $results['cleared_contacts']],
                ['❌ Errors', $results['errors']]
            ]);

            return Command::SUCCESS;

        } catch (\Exception $e) {
            $this->error('❌ Error clearing contacts: ' . $e->getMessage());
            Log::error('Error clearing contacts', [
                'error' => $e->getMessage()
            ]);
            return Command::FAILURE;
        }
    }

    /**
     * Delete all contact folders from Microsoft Graph
     *
     * @return int
     */
    protected function deleteAllContactFolders()
    {
        $this->info('🗑️ Deleting ALL contact folders from Microsoft Graph...');
        $this->error('⚠️ THIS IS A DESTRUCTIVE OPERATION!');
        $this->warn('⚠️ This will PERMANENTLY DELETE ALL contact folders and contacts!');

        if (!$this->option('dry-run')) {
            $this->warn('⚠️ You are about to DELETE ALL CONTACT FOLDERS from Microsoft Graph!');
            $this->warn('⚠️ This action cannot be undone!');

            if (!$this->confirm('Are you absolutely sure you want to delete ALL contact folders?')) {
                $this->info('❌ Operation cancelled by user');
                return Command::SUCCESS;
            }

            // Double confirmation for safety
            if (!$this->confirm('This will permanently delete everything. Type "yes" to confirm', false)) {
                $this->info('❌ Operation cancelled by user');
                return Command::SUCCESS;
            }
        }

        try {
            $results = $this->syncService->deleteAllContactFolders($this->option('dry-run'));

            $this->info('📊 Contact Folder Deletion Results:');
            $this->table(['Metric', 'Count'], [
                ['🗑️ Folders Deleted', $results['deleted_folders']],
                ['🏛️ Committees Cleaned', $results['committees_cleaned'] ?? 0],
                ['👨‍💼 Workgroups Cleaned', $results['workgroups_cleaned'] ?? 0],
                ['❌ Errors', $results['errors']]
            ]);            if ($results['deleted_folders'] > 0) {
                $this->info("✅ Successfully deleted {$results['deleted_folders']} contact folders");

                $totalCleaned = ($results['committees_cleaned'] ?? 0) + ($results['workgroups_cleaned'] ?? 0);
                if ($totalCleaned > 0 && !$this->option('dry-run')) {
                    $this->info("🧹 Cleaned ms_id from {$results['committees_cleaned']} committees and {$results['workgroups_cleaned']} workgroups");
                }

                if (!$this->option('dry-run')) {
                    $this->info('💡 You can now run a fresh sync to recreate the folder structure');
                }
            } else {
                $this->info('📭 No contact folders found to delete');
            }

            return Command::SUCCESS;

        } catch (\Exception $e) {
            $this->error('❌ Error deleting contact folders: ' . $e->getMessage());
            Log::error('Error deleting contact folders', [
                'error' => $e->getMessage()
            ]);
            return Command::FAILURE;
        }
    }

    /**
     * Delete EVERYTHING - contact folders from Microsoft Graph AND local database
     */
    protected function deleteEverything()
    {
        $this->info('🗑️ Deleting EVERYTHING - Microsoft Graph AND local database...');
        $this->error('⚠️ THIS IS AN ULTRA DESTRUCTIVE OPERATION!');
        $this->warn('⚠️ This will PERMANENTLY DELETE:');
        $this->warn('   - ALL contact folders and contacts from Microsoft Graph');
        $this->warn('   - ALL contact_folders and contacts records from local database');

        if (!$this->option('dry-run')) {
            $this->warn('🚨 YOU ARE ABOUT TO DELETE EVERYTHING! 🚨');
            $this->warn('⚠️ This action cannot be undone!');

            if (!$this->confirm('Are you absolutely sure you want to delete EVERYTHING?')) {
                $this->info('❌ Operation cancelled by user');
                return Command::SUCCESS;
            }

            // Triple confirmation for safety
            if (!$this->confirm('This will permanently delete ALL data from both Microsoft Graph AND local database. Type "yes" to confirm', false)) {
                $this->info('❌ Operation cancelled by user');
                return Command::SUCCESS;
            }

            // Final confirmation
            if (!$this->confirm('Last chance! This will destroy ALL contact data. Are you really sure?', false)) {
                $this->info('❌ Operation cancelled by user');
                return Command::SUCCESS;
            }
        }

        try {
            $this->info('🚀 Starting complete cleanup...');
            $results = $this->syncService->deleteAllContactFoldersAndContacts($this->option('dry-run'));

            $this->info('📊 Complete Cleanup Results:');
            $this->table(['Metric', 'Count'], [
                ['🌐 Microsoft Graph Folders Deleted', $results['msgraph_folders_deleted']],
                ['🌐 Microsoft Graph Contacts Deleted', $results['msgraph_contacts_deleted']],
                ['💾 Local Contact Folders Deleted', $results['local_folders_deleted']],
                ['💾 Local Contacts Deleted', $results['local_contacts_deleted']],
                ['❌ Errors', count($results['errors'])]
            ]);

            $totalFolders = $results['msgraph_folders_deleted'] + $results['local_folders_deleted'];
            $totalContacts = $results['msgraph_contacts_deleted'] + $results['local_contacts_deleted'];

            if ($totalFolders > 0 || $totalContacts > 0) {
                $this->info("✅ Successfully deleted {$totalFolders} total folders and {$totalContacts} total contacts");

                if (!$this->option('dry-run')) {
                    $this->info('🧹 Database is now completely clean');
                    $this->info('💡 You can now run a fresh sync to recreate everything from scratch');
                } else {
                    $this->info('🧪 DRY RUN: Nothing was actually deleted');
                }
            } else {
                $this->info('📭 No data found to delete');
            }

            if (!empty($results['errors'])) {
                $this->warn('⚠️ Some errors occurred during cleanup:');
                foreach ($results['errors'] as $error) {
                    $this->error("  - {$error}");
                }
            }

            return Command::SUCCESS;

        } catch (\Exception $e) {
            $this->error('❌ Error during complete cleanup: ' . $e->getMessage());
            Log::error('Error during complete cleanup', [
                'error' => $e->getMessage()
            ]);
            return Command::FAILURE;
        }
    }

    /**
     * Get a user from Microsoft Graph by email or ID
     *
     * @param string $identifier The email or ID of the user
     * @return int
     */
    protected function getUserFromGraph(string $identifier)
    {
        $this->info("🔍 Fetching user from Microsoft Graph: {$identifier}");

        try {
            // Use the API client directly to get user information
            $apiClient = app(MicrosoftGraphApiClient::class);
            $apiClient->initialize();

            // Perform GET /users/{id|userPrincipalName}
            $endpoint = "users/" . urlencode($identifier);
            $response = $apiClient->getWithRetry($endpoint, ['operation' => 'get_user']);

            if (!$response) {
                $this->error('❌ No response received from Microsoft Graph API');
                return Command::FAILURE;
            }

            $this->info("✅ User found in Microsoft Graph:");
            $this->newLine();

            // Convert response to array if it's an object
            $userArray = is_object($response) ? json_decode(json_encode($response), true) : $response;

            // Display user information in a readable format
            $this->displayUserInfo($userArray);

            // Also display raw JSON response
            $this->newLine();
            $this->info("📋 Raw Microsoft Graph Response:");
            $this->line(json_encode($response, JSON_PRETTY_PRINT));

            return Command::SUCCESS;

        } catch (\Exception $e) {
            $this->error('❌ Error fetching user from Microsoft Graph: ' . $e->getMessage());

            // Check if it's a 404 error (user not found)
            if (strpos($e->getMessage(), '404') !== false || strpos($e->getMessage(), 'not found') !== false) {
                $this->warn("💡 User '{$identifier}' was not found in Microsoft Graph");
                $this->info("   Make sure the email or ID is correct and the user exists in your tenant");
            }

            Log::error('Error fetching user from Microsoft Graph', [
                'identifier' => $identifier,
                'error' => $e->getMessage()
            ]);
            return Command::FAILURE;
        }
    }

    /**
     * Sync a specific contact by user_id and folder_id
     *
     * @param string $contactSpec The contact specification in format "user_id,folder_id"
     * @return int
     */
    protected function syncSpecificContact(string $contactSpec)
    {
        // Parse the contact specification
        $parts = explode(',', $contactSpec);
        if (count($parts) !== 2) {
            $this->error('❌ Invalid format. Use: --sync-specific-contact=user_id,folder_id');
            $this->info('💡 Example: --sync-specific-contact=1045,744');
            return Command::FAILURE;
        }

        $userId = (int) trim($parts[0]);
        $folderId = (int) trim($parts[1]);

        $this->info("🔄 Syncing specific contact...");
        $this->info("👤 User ID: {$userId}");
        $this->info("📁 Folder ID: {$folderId}");

        if ($this->option('dry-run')) {
            $this->warn('⚠️  Running in DRY-RUN mode - no changes will be made');
        }

        try {
            // Get the user from database
            $user = User::find($userId);
            if (!$user) {
                $this->error("❌ User with ID {$userId} not found in database");
                return Command::FAILURE;
            }

            // Get the contact folder from database
            $contactFolder = ContactFolder::find($folderId);
            if (!$contactFolder) {
                $this->error("❌ Contact folder with ID {$folderId} not found in database");
                return Command::FAILURE;
            }

            // Get the Microsoft user (service user)
            $microsoftUser = $contactFolder->microsoftUser;
            if (!$microsoftUser) {
                $this->error("❌ No Microsoft user associated with contact folder {$folderId}");
                return Command::FAILURE;
            }

            $this->info("✅ Found user: {$user->name} ({$user->email})");
            $this->info("✅ Found folder: {$contactFolder->display_name}");
            $this->info("✅ Microsoft user: {$microsoftUser->email}");

            // Check if contact already exists (search by email since contacts table doesn't have user_id)
            $existingContact = Contact::where('contact_folder_id', $folderId)
                                     ->where('email', $user->email)
                                     ->first();

            if ($existingContact) {
                $this->warn("⚠️  Contact already exists in database with ID: {$existingContact->id}");
                if (!$this->confirm('Do you want to recreate this contact?')) {
                    $this->info('❌ Operation cancelled by user');
                    return Command::SUCCESS;
                }

                // Delete existing contact from Microsoft Graph if it has ms_contact_id
                if ($existingContact->ms_contact_id) {
                    $this->info("🗑️  Deleting existing contact from Microsoft Graph...");
                    try {
                        $apiClient = app(MicrosoftGraphApiClient::class);
                        $apiClient->initialize();
                        $apiClient->setDryRun($this->option('dry-run'));

                        if (!$this->option('dry-run')) {
                            $apiClient->deleteWithRetry(
                                "users/{$microsoftUser->ms_id}/contactFolders/{$contactFolder->ms_folder_id}/contacts/{$existingContact->ms_contact_id}",
                                [
                                    'operation' => 'delete_existing_contact',
                                    'user_name' => $user->name,
                                    'folder_name' => $contactFolder->display_name
                                ]
                            );
                        }
                        $this->info("✅ Existing contact deleted from Microsoft Graph");
                    } catch (\Exception $e) {
                        $this->warn("⚠️  Failed to delete existing contact from Microsoft Graph: " . $e->getMessage());
                        $this->info("Continuing with creation...");
                    }
                }

                // Delete from local database
                if (!$this->option('dry-run')) {
                    $existingContact->delete();
                }
                $this->info("✅ Existing contact deleted from local database");
            }

            // Create the contact using the contact service
            $contactService = app(MicrosoftGraphContactService::class);

            $this->info("📝 Creating contact in Microsoft Graph...");

            $success = $contactService->createContactForUser($user, $contactFolder, $this->option('dry-run'));

            if ($success) {
                $this->info("✅ Contact created successfully!");
                $this->table(['Property', 'Value'], [
                    ['User Name', $user->name],
                    ['User Email', $user->email],
                    ['Folder Name', $contactFolder->display_name],
                    ['Microsoft User', $microsoftUser->email],
                    ['Dry Run', $this->option('dry-run') ? 'Yes' : 'No']
                ]);

                return Command::SUCCESS;
            } else {
                $this->error("❌ Failed to create contact");
                $this->warn("💡 This might be due to:");
                $this->warn("   - Microsoft Graph service unavailability (503 errors)");
                $this->warn("   - Network connectivity issues");
                $this->warn("   - Permission issues");
                $this->warn("   - Invalid contact data");

                return Command::FAILURE;
            }

        } catch (\Exception $e) {
            $this->error('❌ Error syncing specific contact: ' . $e->getMessage());
            Log::error('Error syncing specific contact', [
                'user_id' => $userId,
                'folder_id' => $folderId,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return Command::FAILURE;
        }
    }

    /**
     * Display user information in a readable format
     *
     * @param array $user
     */
    protected function displayUserInfo(array $user)
    {
        $userInfo = [
            ['Property', 'Value'],
            ['Display Name', $user['displayName'] ?? 'N/A'],
            ['User Principal Name', $user['userPrincipalName'] ?? 'N/A'],
            ['Mail', $user['mail'] ?? 'N/A'],
            ['ID', $user['id'] ?? 'N/A'],
            ['Job Title', $user['jobTitle'] ?? 'N/A'],
            ['Department', $user['department'] ?? 'N/A'],
            ['Company Name', $user['companyName'] ?? 'N/A'],
            ['Office Location', $user['officeLocation'] ?? 'N/A'],
            ['Mobile Phone', $user['mobilePhone'] ?? 'N/A'],
            ['Business Phones', is_array($user['businessPhones'] ?? null) ? implode(', ', $user['businessPhones']) : 'N/A'],
            ['Account Enabled', ($user['accountEnabled'] ?? null) ? 'Yes' : 'No'],
            ['User Type', $user['userType'] ?? 'N/A'],
        ];

        $this->table(['Property', 'Value'], array_slice($userInfo, 1));
    }

    /**
     * Get a contact from Microsoft Graph by contact ID
     *
     * @param string $contactId The Microsoft Graph contact ID
     * @return int
     */
    protected function getContactFromGraph(string $contactId)
    {
        $this->info("🔍 Fetching contact from Microsoft Graph: {$contactId}");

        try {
            // Use the API client directly to get contact information
            $apiClient = app(MicrosoftGraphApiClient::class);
            $apiClient->initialize();

            // First, we need to find which user/folder contains this contact
            // Since we don't know the user and folder, we'll need to search through service users
            $serviceUsers = MicrosoftUser::whereNotNull('ms_id')->get();

            if ($serviceUsers->isEmpty()) {
                $this->error('❌ No service users found in database');
                $this->warn('💡 Make sure you have service users configured with ms_id values');
                return Command::FAILURE;
            }

            $this->info("🔍 Searching through {$serviceUsers->count()} service users...");

            $contactFound = false;
            $contactData = null;
            $foundInUser = null;
            $foundInFolder = null;

            foreach ($serviceUsers as $serviceUser) {
                $this->line("   Checking user: {$serviceUser->email}");

                try {
                    // Get all contact folders for this user (handle pagination)
                    $allFolders = [];
                    $foldersEndpoint = "users/{$serviceUser->ms_id}/contactFolders?\$top=100";

                    do {
                        $foldersResponse = $apiClient->getWithRetry($foldersEndpoint, ['operation' => 'get_folders']);

                        if (!$foldersResponse) {
                            Log::warning("No response when fetching folders for user {$serviceUser->email}");
                            break;
                        }

                        $responseValue = $foldersResponse['value'];
                        Log::info("Fetched " . count($responseValue ?? []) . " folders for user {$serviceUser->email}");
                        Log::info("Folder response: " . $responseValue);
                        Log::info("Folder response json: " . json_encode($responseValue));
                        Log::info("Folder details: " . $responseValue['value']);
                        Log::info("Next link: " . $responseValue['@odata.nextLink']);

                        $folders = $responseValue['value'] ?? null;
                        $nextLink = $responseValue['@odata.nextLink'] ?? null;

                        // Add folders from this page
                        $allFolders = array_merge($allFolders, $folders);

                        $foldersEndpoint = $nextLink;

                    } while ($nextLink);

                    if (empty($allFolders)) {
                        continue;
                    }

                    $this->line("   Found {" . count($allFolders) . "} folders for this user");

                    // Search through each folder
                    foreach ($allFolders as $folder) {
                        $this->line("   Checking folder: {$folder->displayName} ({$folder->id})");
                        try {
                            // Try to get the specific contact from this folder
                            $contactEndpoint = "users/{$serviceUser->ms_id}/contactFolders/{$folder->id}/contacts/{$contactId}";
                            $contactResponse = $apiClient->getWithRetry($contactEndpoint, ['operation' => 'get_contact']);

                            if ($contactResponse) {
                                $contactFound = true;
                                $contactData = $contactResponse;
                                $foundInUser = $serviceUser;
                                $foundInFolder = $folder;
                                break 2; // Break out of both loops
                            }
                        } catch (\Exception $e) {
                            // Contact not found in this folder, continue searching
                            if (strpos($e->getMessage(), '404') === false) {
                                // Only log non-404 errors
                                $this->line("     Warning in folder {$folder->displayName}: " . $e->getMessage());
                            }
                            continue;
                        }
                    }
                } catch (\Exception $e) {
                    $this->line("     Error accessing user {$serviceUser->email}: " . $e->getMessage());
                    continue;
                }
            }

            if (!$contactFound) {
                $this->error("❌ Contact with ID '{$contactId}' not found in any service user's contact folders");
                $this->warn("💡 Make sure:");
                $this->warn("   - The contact ID is correct");
                $this->warn("   - The contact exists in Microsoft Graph");
                $this->warn("   - Service users have proper permissions");
                return Command::FAILURE;
            }

            $this->info("✅ Contact found in Microsoft Graph!");
            $this->newLine();

            // Display contact location info
            $this->info("📍 Contact Location:");
            $this->table(['Property', 'Value'], [
                ['Service User', $foundInUser->name . ' (' . $foundInUser->email . ')'],
                ['Folder Name', $foundInFolder->displayName],
                ['Folder ID', $foundInFolder->id]
            ]);
            $this->newLine();

            // Convert response to array if it's an object
            $contactArray = is_object($contactData) ? json_decode(json_encode($contactData), true) : $contactData;

            // Display contact information in a readable format
            $this->displayContactInfo($contactArray);

            // Also display raw JSON response
            $this->newLine();
            $this->info("📋 Raw Microsoft Graph Response:");
            $this->line(json_encode($contactData, JSON_PRETTY_PRINT));

            // Check if this contact exists in our local database
            $this->newLine();
            $this->info("🔍 Checking local database...");
            $localContact = Contact::where('ms_contact_id', $contactId)->first();

            if ($localContact) {
                $this->info("✅ Contact found in local database:");
                $this->table(['Property', 'Value'], [
                    ['Local ID', $localContact->id],
                    ['Email', $localContact->email],
                    ['Display Name', $localContact->display_name],
                    ['Contact Folder ID', $localContact->contact_folder_id],
                    ['Created At', $localContact->created_at],
                    ['Updated At', $localContact->updated_at]
                ]);
            } else {
                $this->warn("⚠️  Contact not found in local database");
                $this->info("💡 This might be a contact that was created manually in Microsoft Graph");
            }

            return Command::SUCCESS;

        } catch (\Exception $e) {
            $this->error('❌ Error fetching contact from Microsoft Graph: ' . $e->getMessage());
            Log::error('Error fetching contact from Microsoft Graph', [
                'contact_id' => $contactId,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return Command::FAILURE;
        }
    }

    /**
     * Display contact information in a readable format
     *
     * @param array $contact
     */
    protected function displayContactInfo(array $contact)
    {
        $this->info("📧 Contact Information:");

        $contactInfo = [
            ['Property', 'Value'],
            ['Display Name', $contact['displayName'] ?? 'N/A'],
            ['Given Name', $contact['givenName'] ?? 'N/A'],
            ['Surname', $contact['surname'] ?? 'N/A'],
            ['Company Name', $contact['companyName'] ?? 'N/A'],
            ['Job Title', $contact['jobTitle'] ?? 'N/A'],
            ['Department', $contact['department'] ?? 'N/A'],
            ['Office Location', $contact['officeLocation'] ?? 'N/A'],
            ['ID', $contact['id'] ?? 'N/A'],
            ['Created DateTime', $contact['createdDateTime'] ?? 'N/A'],
            ['Last Modified DateTime', $contact['lastModifiedDateTime'] ?? 'N/A'],
        ];

        // Handle email addresses
        if (isset($contact['emailAddresses']) && is_array($contact['emailAddresses'])) {
            foreach ($contact['emailAddresses'] as $index => $email) {
                $emailLabel = count($contact['emailAddresses']) > 1 ? "Email " . ($index + 1) : "Email";
                $emailValue = is_array($email) ? ($email['address'] ?? 'N/A') : 'N/A';
                $contactInfo[] = [$emailLabel, $emailValue];
            }
        } else {
            $contactInfo[] = ['Email', 'N/A'];
        }

        // Handle phone numbers
        if (isset($contact['businessPhones']) && is_array($contact['businessPhones'])) {
            $contactInfo[] = ['Business Phones', implode(', ', $contact['businessPhones'])];
        } else {
            $contactInfo[] = ['Business Phones', 'N/A'];
        }

        if (isset($contact['mobilePhone'])) {
            $contactInfo[] = ['Mobile Phone', $contact['mobilePhone']];
        }

        if (isset($contact['homePhones']) && is_array($contact['homePhones'])) {
            $contactInfo[] = ['Home Phones', implode(', ', $contact['homePhones'])];
        }

        // Handle business address
        if (isset($contact['businessAddress']) && is_array($contact['businessAddress'])) {
            $address = $contact['businessAddress'];
            $addressParts = array_filter([
                $address['street'] ?? '',
                $address['city'] ?? '',
                $address['state'] ?? '',
                $address['postalCode'] ?? '',
                $address['countryOrRegion'] ?? ''
            ]);
            $contactInfo[] = ['Business Address', implode(', ', $addressParts) ?: 'N/A'];
        }

        $this->table(['Property', 'Value'], array_slice($contactInfo, 1));
    }
}
