<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Modules\Twilio\Services\TwilioServiceInterface;
use App\Models\Setting;

class TestTwilioIntegration extends Command
{
    protected $signature = 'twilio:test {phone? : Phone number to send test SMS to}';
    protected $description = 'Test Twilio SMS integration';

    public function handle()
    {
        $this->info('Testing Twilio SMS Integration...');
        $this->line('=====================================');
        
        // Check settings
        $this->info('1. Checking Settings:');
        $smsEnabled = Setting::get('notifications.sms_enabled', false);
        $twilioEnabled = Setting::get('integrations.twilio.enabled', false);
        $accountSid = Setting::get('integrations.twilio.account_sid', '');
        $authToken = Setting::get('integrations.twilio.auth_token', '');
        $fromNumber = Setting::get('integrations.twilio.from_number', '');
        
        $this->line('   SMS Notifications: ' . ($smsEnabled ? '✓ Enabled' : '✗ Disabled'));
        $this->line('   Twilio Integration: ' . ($twilioEnabled ? '✓ Enabled' : '✗ Disabled'));
        $this->line('   Account SID: ' . ($accountSid ? '✓ Set (' . substr($accountSid, 0, 10) . '...)' : '✗ Not Set'));
        $this->line('   Auth Token: ' . ($authToken ? '✓ Set' : '✗ Not Set'));
        $this->line('   From Number: ' . ($fromNumber ?: '✗ Not Set'));
        
        // Check environment
        $this->line('');
        $this->info('2. Environment:');
        $env = app()->environment();
        $this->line('   Current: ' . $env);
        
        if (in_array($env, ['local', 'testing'])) {
            $this->warn('   ⚠ Running in fake mode - no actual SMS will be sent');
        } else {
            $this->line('   ✓ Production mode - will send real SMS');
        }
        
        // Test service initialization
        $this->line('');
        $this->info('3. Service Initialization:');
        
        try {
            $twilioService = app(TwilioServiceInterface::class);
            $this->line('   ✓ TwilioService initialized successfully');
        } catch (\Exception $e) {
            $this->error('   ✗ Failed to initialize: ' . $e->getMessage());
            return 1;
        }
        
        // Send test SMS if phone number provided
        $phoneNumber = $this->argument('phone');
        if ($phoneNumber) {
            $this->line('');
            $this->info('4. Sending Test SMS:');
            $this->line('   To: ' . $phoneNumber);
            
            try {
                $result = $twilioService->testSMS(
                    $phoneNumber,
                    'Test SMS from Seraph - Twilio integration is working!'
                );
                
                if ($result['success']) {
                    $this->line('   ✓ SMS sent successfully!');
                    $this->line('   Message SID: ' . $result['message_sid']);
                    $this->line('   Status: ' . $result['status']);
                    
                    // If in fake mode, note it
                    if (str_starts_with($result['message_sid'], 'FAKE')) {
                        $this->warn('   Note: This was a fake response (local/testing environment)');
                    }
                } else {
                    $this->error('   ✗ Failed to send SMS: ' . $result['error']);
                }
            } catch (\Exception $e) {
                $this->error('   ✗ Exception: ' . $e->getMessage());
            }
        } else {
            $this->line('');
            $this->comment('Tip: Run with a phone number to send a test SMS');
            $this->comment('Example: php artisan twilio:test +447987654321');
        }
        
        // Test task completion SMS
        $this->line('');
        $this->info('5. Testing Task Completion SMS:');
        
        if (!$phoneNumber) {
            $this->comment('   Skipped - provide phone number to test');
        } else {
            try {
                $result = $twilioService->sendCompletionSMS(
                    999, // Fake task ID
                    $phoneNumber,
                    'Task #999 has been completed. Thank you!'
                );
                
                if ($result['success']) {
                    $this->line('   ✓ Completion SMS sent successfully!');
                    if (isset($result['notification_id'])) {
                        $this->line('   Notification ID: ' . $result['notification_id']);
                    }
                } else {
                    $this->error('   ✗ Failed: ' . $result['error']);
                }
            } catch (\Exception $e) {
                $this->error('   ✗ Exception: ' . $e->getMessage());
            }
        }
        
        $this->line('');
        $this->info('Test completed!');
        
        return 0;
    }
}