<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\MicrosoftGraphSyncService;
use Exception;

class DebugMsgraphCommand extends Command
{
    protected $signature = 'debug:msgraph';
    protected $description = 'Debug Microsoft Graph connection';

    public function handle()
    {
        $this->info('🔍 Debugging Microsoft Graph...');

        try {
            // Check environment variables
            $this->info('📋 Environment Check:');
            $this->table(['Variable', 'Status'], [
                ['MSGRAPH_CLIENT_ID', env('MSGRAPH_CLIENT_ID') ? '✅ SET' : '❌ NOT_SET'],
                ['MSGRAPH_SECRET_ID', env('MSGRAPH_SECRET_ID') ? '✅ SET' : '❌ NOT_SET'],
                ['MSGRAPH_TENANT_ID', env('MSGRAPH_TENANT_ID') ? '✅ SET' : '❌ NOT_SET'],
                ['MSGRAPH_SERVICE_USER_ID', env('MSGRAPH_SERVICE_USER_ID') ? '✅ SET' : '❌ NOT_SET'],
            ]);

            // Test service
            $this->info('🔧 Creating service...');
            $service = new MicrosoftGraphSyncService();
            $this->info('✅ Service created successfully');

            // Test contact folder creation at root level
            $this->info('📁 Testing contact folder creation at root level...');
            $result = $service->syncContactFolders(true); // dry-run
            $this->info('📊 Dry-run result: ' . json_encode($result));

            // Test real connection
            $this->info('🔌 Testing real connection...');
            $connectionResult = $service->testConnection();
            $this->info('📊 Connection result: ' . json_encode($connectionResult));

        } catch (Exception $e) {
            $this->error('❌ Error: ' . $e->getMessage());
            $this->error('📍 File: ' . $e->getFile() . ':' . $e->getLine());
            $this->line('🔍 Trace:');
            $this->line($e->getTraceAsString());
        }
    }
}
