<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\FirebaseConfigurationService;
use App\Services\FirebaseService;

class TestFirebase extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'firebase:test
                            {--setup : Show Firebase setup instructions}
                            {--test-connection : Test Firebase connection}
                            {--validate : Validate Firebase configuration}
                            {--all : Run all tests}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Test Firebase configuration and connection';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $firebaseConfigService = new FirebaseConfigurationService();
        $firebaseService = new FirebaseService();

        $this->info('🧪 Testing Firebase Configuration...');
        $this->line('');

        // Show setup instructions if requested
        if ($this->option('setup')) {
            $this->showSetupInstructions();
            return 0;
        }

        // Validate configuration
        if ($this->option('validate') || $this->option('all')) {
            $this->validateConfiguration($firebaseConfigService);
        }

        // Test connection
        if ($this->option('test-connection') || $this->option('all')) {
            $this->testConnection($firebaseConfigService, $firebaseService);
        }

        // Test notification sending if all options are selected
        if ($this->option('all')) {
            $this->testNotificationSending($firebaseService);
        }

        $this->info('✅ Firebase testing completed!');
        return 0;
    }

    /**
     * Show Firebase setup instructions
     */
    protected function showSetupInstructions()
    {
        $this->info('📋 Firebase Setup Instructions');
        $this->line('');

        $instructions = (new FirebaseConfigurationService())->getSetupInstructions();

        foreach ($instructions as $step => $data) {
            $this->info("Step " . str_replace('step', '', $step) . ": " . $data['title']);
            $this->line($data['description']);
            $this->line("URL: " . $data['url']);
            $this->line('');
        }

        $this->info('🔧 Environment Configuration Example:');
        $this->line('');
        
        $envExample = $instructions['step4']['env_example'];
        foreach ($envExample as $key => $value) {
            $this->line("<fg=yellow>$key</>=$value");
        }
        $this->line('');
    }

    /**
     * Validate Firebase configuration
     */
    protected function validateConfiguration(FirebaseConfigurationService $service)
    {
        $this->info('🔍 Validating Firebase Configuration...');
        $this->line('');

        $status = $service->getConfigurationStatus();

        if ($status['configured']) {
            $this->info('✅ Firebase configuration is complete!');
            $this->line('');
            $this->table(
                ['Setting', 'Value'],
                [
                    ['Project ID', $status['project_id']],
                    ['Client Email', $status['client_email']],
                    ['Private Key', $status['has_private_key'] ? '✅ Present' : '❌ Missing'],
                    ['Server Key', $status['has_server_key'] ? '✅ Present' : '❌ Missing'],
                    ['API Key', $status['has_api_key'] ? '✅ Present' : '❌ Missing'],
                    ['Database URL', $status['database_url']],
                    ['Storage Bucket', $status['storage_bucket']],
                    ['Sender ID', $status['sender_id']],
                    ['App ID', $status['app_id']],
                    ['Measurement ID', $status['measurement_id']],
                ]
            );
        } else {
            $this->error('❌ Firebase configuration is incomplete!');
            $this->line('');
            $this->error('Missing required settings:');
            foreach ($status['errors'] as $error) {
                $this->error("- $error");
            }
            $this->line('');
            $this->warn('💡 Run: php artisan firebase:test --setup');
            $this->warn('   to see detailed setup instructions.');
            $this->line('');
        }
    }

    /**
     * Test Firebase connection
     */
    protected function testConnection(FirebaseConfigurationService $configService, FirebaseService $firebaseService)
    {
        $this->info('🔌 Testing Firebase Connection...');
        $this->line('');

        // Test basic configuration
        $config = $configService->getConfigurationStatus();
        
        if (!$config['configured']) {
            $this->error('❌ Cannot test connection - configuration is incomplete');
            $this->line('');
            return;
        }

        // Test Firebase SDK initialization
        try {
            $credentials = $configService->getCredentials();
            
            if (empty($credentials['projectId']) || empty($credentials['privateKey'])) {
                $this->error('❌ Firebase SDK initialization failed - missing required credentials');
                $this->line('');
                return;
            }

            // Test Firebase service creation
            $this->info('Testing Firebase service creation...');
            
            // Test messaging configuration
            $messagingConfig = $configService->getMessagingConfig();
            if (empty($messagingConfig['server_key'])) {
                $this->error('❌ Firebase Server Key is missing for messaging');
                $this->line('');
                return;
            }

            $this->info('✅ Firebase connection test passed!');
            $this->line('');
            $this->info("Project ID: {$credentials['projectId']}");
            $this->info("Server Key: " . substr($messagingConfig['server_key'], 0, 20) . "...");
            $this->line('');

        } catch (\Exception $e) {
            $this->error('❌ Firebase connection test failed!');
            $this->error('Error: ' . $e->getMessage());
            $this->line('');
        }
    }

    /**
     * Test notification sending
     */
    protected function testNotificationSending(FirebaseService $firebaseService)
    {
        $this->info('📨 Testing Notification Sending...');
        $this->line('');

        // Check if Firebase is ready
        $configService = new FirebaseConfigurationService();
        $ready = $configService->isReadyForNotifications();

        if (!$ready['ready']) {
            $this->error('❌ Cannot test notifications - Firebase is not ready');
            $this->error('Reason: ' . $ready['message']);
            $this->line('');
            return;
        }

        // Test notification structure
        $testNotification = [
            'title' => 'Test Notification',
            'message' => 'This is a test notification from CLX Pro',
            'data' => [
                'type' => 'test',
                'timestamp' => now()->toISOString(),
                'app_version' => config('app.version', '1.0.0')
            ]
        ];

        $this->info('Testing notification structure...');
        $this->table(
            ['Field', 'Value'],
            [
                ['Title', $testNotification['title']],
                ['Message', $testNotification['message']],
                ['Type', $testNotification['data']['type']],
                ['Timestamp', $testNotification['data']['timestamp']],
            ]
        );

        $this->info('✅ Notification structure is valid!');
        $this->line('');
        $this->warn('💡 To test actual sending, you need:');
        $this->warn('   1. A registered mobile device with FCM token');
        $this->warn('   2. Firebase credentials properly configured');
        $this->warn('   3. Mobile app running and connected to Firebase');
        $this->line('');
    }
}
