<?php

namespace App\Modules\ThreeCX\Services;

use App\Models\Setting;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

/**
 * 3CX Extension Resolver Service
 * 
 * Centralized logic for determining which extension to use for calls
 * Based on user role, user profile settings, and admin configuration
 */
class ThreeCXExtensionResolver
{
    /**
     * Get the appropriate extension for the current user
     * 
     * For Admins: Always use integration settings extension (for testing flexibility)
     * For Regular Users: Use user profile extension first, fallback to integration settings
     * 
     * @param User|null $user Optional user override (defaults to current auth user)
     * @return string The extension to use for calls
     */
    public static function getExtensionForUser(?User $user = null): string
    {
        $user = $user ?? Auth::user();
        $isAdmin = self::isUserAdmin($user);
        
        // Get the default extension from integration settings
        $defaultExtension = Setting::get('integrations.threecx.extension', '324');
        
        // Only log when there's a user context to reduce WebSocket polling noise
        if ($user) {
            Log::info('[3CX Extension Resolver] Determining extension', [
                'user_id' => $user->id,
                'user_email' => $user->email,
                'is_admin' => $isAdmin,
                'default_extension' => $defaultExtension,
                'user_extension' => $user->extension
            ]);
        } else {
            Log::debug('[3CX Extension Resolver] No user context - using default extension', [
                'default_extension' => $defaultExtension
            ]);
        }
        
        // For admins: Always use integration settings extension for testing flexibility
        if ($isAdmin) {
            Log::info('[3CX Extension Resolver] Admin user - using integration settings extension', [
                'extension' => $defaultExtension
            ]);
            return $defaultExtension;
        }
        
        // For regular users: Use their profile extension first, fallback to default
        if ($user && !empty($user->extension)) {
            Log::info('[3CX Extension Resolver] Regular user - using profile extension', [
                'user_extension' => $user->extension
            ]);
            return (string) $user->extension;
        }
        
        // Fallback to integration settings extension
        Log::debug('[3CX Extension Resolver] Using fallback extension from integration settings', [
            'fallback_extension' => $defaultExtension
        ]);
        return $defaultExtension;
    }
    
    /**
     * Determine if a user is an admin
     * 
     * @param User|null $user
     * @return bool
     */
    protected static function isUserAdmin(?User $user): bool
    {
        if (!$user) {
            return false;
        }
        
        // Check if user email contains administrator
        $email = strtolower($user->email ?? '');
        if (str_contains($email, 'administrator')) {
            Log::info('[3CX Extension Resolver] Admin detected via email', [
                'email' => $email
            ]);
            return true;
        }
        
        // Check if user role contains admin-like keywords
        $role = strtolower($user->role ?? '');
        $adminKeywords = ['admin', 'administrator', 'manager', 'supervisor'];
        
        foreach ($adminKeywords as $keyword) {
            if (str_contains($role, $keyword)) {
                Log::info('[3CX Extension Resolver] Admin detected via role', [
                    'role' => $role,
                    'keyword' => $keyword
                ]);
                return true;
            }
        }
        
        // Check if user ID is 1 (typically the first admin user)
        if ($user->id === 1) {
            Log::info('[3CX Extension Resolver] Admin detected via user ID = 1');
            return true;
        }
        
        Log::info('[3CX Extension Resolver] Not detected as admin', [
            'user_id' => $user->id,
            'email' => $email,
            'role' => $role
        ]);
        
        return false;
    }
    
    /**
     * Get extension for API/test calls (always uses integration settings)
     * 
     * @return string
     */
    public static function getExtensionForApiCall(): string
    {
        $extension = Setting::get('integrations.threecx.extension', '324');
        
        Log::info('[3CX Extension Resolver] API call extension', [
            'extension' => $extension
        ]);
        
        return $extension;
    }
}
