<?php

namespace App\Services;

use App\Models\Setting;
use App\Modules\Twilio\Services\TwilioService;
use App\Modules\TextMagic\Services\TextMagicService;
use Illuminate\Support\Facades\Log;

/**
 * SMS Manager - Handles SMS sending through multiple providers
 * Automatically selects the active provider based on settings
 */
class SmsManager
{
    protected $activeProvider = null;
    protected $twilioService = null;
    protected $textMagicService = null;

    public function __construct()
    {
        $this->detectActiveProvider();
        // Only instantiate the active provider service
        $this->initializeActiveService();
    }

    /**
     * Initialize only the active SMS service
     */
    protected function initializeActiveService()
    {
        if ($this->activeProvider === 'textmagic') {
            $this->textMagicService = new TextMagicService();
        } elseif ($this->activeProvider === 'twilio') {
            $this->twilioService = new TwilioService();
        }
    }

    /**
     * Detect which SMS provider is currently enabled
     */
    protected function detectActiveProvider()
    {
        // Check if TextMagic is enabled
        if (Setting::get('integrations.textmagic.enabled', false)) {
            $this->activeProvider = 'textmagic';
            Log::debug('[SMS Manager] Active provider: TextMagic');
            return;
        }

        // Check if Twilio is enabled
        if (Setting::get('integrations.twilio.enabled', false)) {
            $this->activeProvider = 'twilio';
            Log::debug('[SMS Manager] Active provider: Twilio');
            return;
        }

        // No provider enabled
        $this->activeProvider = null;
        Log::debug('[SMS Manager] No SMS provider enabled');
    }

    /**
     * Get the active SMS service
     */
    protected function getActiveService()
    {
        if ($this->activeProvider === 'textmagic') {
            return $this->textMagicService;
        }

        if ($this->activeProvider === 'twilio') {
            return $this->twilioService;
        }

        throw new \Exception('No SMS provider is enabled. Please configure Twilio or TextMagic in settings.');
    }

    /**
     * Send SMS message
     */
    public function sendSMS(string $to, string $message, ?array $options = []): array
    {
        try {
            $service = $this->getActiveService();
            $result = $service->sendSMS($to, $message, $options);

            // Normalize response format
            return [
                'success' => $result['success'] ?? false,
                'message_sid' => $result['message_sid'] ?? $result['message_id'] ?? null,
                'status' => $result['status'] ?? 'unknown',
                'to' => $result['to'] ?? $to,
                'provider' => $this->activeProvider,
                'error' => $result['error'] ?? null
            ];

        } catch (\Exception $e) {
            Log::error('[SMS Manager] Failed to send SMS', [
                'provider' => $this->activeProvider,
                'to' => $to,
                'error' => $e->getMessage()
            ]);

            return [
                'success' => false,
                'error' => $e->getMessage(),
                'provider' => $this->activeProvider
            ];
        }
    }

    /**
     * Send SMS with task context
     */
    public function sendTaskSMS(int $taskId, string $to, string $message): array
    {
        try {
            $service = $this->getActiveService();
            $result = $service->sendTaskSMS($taskId, $to, $message);

            // Normalize response
            return [
                'success' => $result['success'] ?? false,
                'message_sid' => $result['message_sid'] ?? $result['message_id'] ?? null,
                'status' => $result['status'] ?? 'unknown',
                'notification_id' => $result['notification_id'] ?? null,
                'provider' => $this->activeProvider,
                'error' => $result['error'] ?? null
            ];

        } catch (\Exception $e) {
            Log::error('[SMS Manager] Failed to send task SMS', [
                'task_id' => $taskId,
                'provider' => $this->activeProvider,
                'error' => $e->getMessage()
            ]);

            return [
                'success' => false,
                'error' => $e->getMessage(),
                'provider' => $this->activeProvider
            ];
        }
    }

    /**
     * Send completion notification SMS
     */
    public function sendCompletionSMS(int $taskId, string $to, string $message): array
    {
        try {
            $service = $this->getActiveService();
            $result = $service->sendCompletionSMS($taskId, $to, $message);

            // Normalize response
            return [
                'success' => $result['success'] ?? false,
                'message_sid' => $result['message_sid'] ?? $result['message_id'] ?? null,
                'status' => $result['status'] ?? 'unknown',
                'notification_id' => $result['notification_id'] ?? null,
                'provider' => $this->activeProvider,
                'error' => $result['error'] ?? null
            ];

        } catch (\Exception $e) {
            Log::error('[SMS Manager] Failed to send completion SMS', [
                'task_id' => $taskId,
                'provider' => $this->activeProvider,
                'error' => $e->getMessage()
            ]);

            return [
                'success' => false,
                'error' => $e->getMessage(),
                'provider' => $this->activeProvider
            ];
        }
    }

    /**
     * Test SMS configuration
     */
    public function testSMS(string $to, string $message): array
    {
        try {
            $service = $this->getActiveService();
            return $service->testSMS($to, $message);
        } catch (\Exception $e) {
            return [
                'success' => false,
                'error' => $e->getMessage(),
                'provider' => $this->activeProvider
            ];
        }
    }

    /**
     * Get active provider name
     */
    public function getActiveProvider(): ?string
    {
        return $this->activeProvider;
    }

    /**
     * Check if SMS is available
     */
    public function isAvailable(): bool
    {
        return $this->activeProvider !== null;
    }
}
