<?php

namespace App\Services\MicrosoftGraph;

use Illuminate\Support\Facades\Log;

/**
 * Utility functions for Microsoft Graph operations
 * Handles sanitization, validation, and model helpers
 */
class MicrosoftGraphUtilities
{
    /**
     * Get the display title for a model
     */
    public static function getModelTitle($model): string
    {
        // Fallback to direct title attribute
        return $model->title ?? 'Untitled';
    }

    /**
     * Sanitize folder display name for Microsoft Graph API
     * Removes special characters that can cause API errors
     */
    public static function sanitizeFolderDisplayName(string $displayName): string
    {
        Log::info("🧹 Sanitizing folder name: '{$displayName}'");

        // Replace problematic characters with safe alternatives
        $sanitized = str_replace([
            '/', '\\', ':', '*', '?', '"', '<', '>', '|',  // File system reserved chars
            '&', '%', '#', '@', '!', '$', '^', '+', '=',   // Special chars that can cause issues
            '[', ']', '{', '}', '(', ')',                   // Brackets
            '~', '`', ';', ',', '.'                         // Other potentially problematic chars
        ], [
            '-', '-', '-', '-', '-', '-', '-', '-', '-',   // Replace with dashes
            'and', 'pct', 'num', 'at', '', '', '', 'plus', 'eq',  // Some with words
            '', '', '', '', '', '',                         // Remove brackets
            '', '', '', '', ''                              // Remove other chars
        ], $displayName);

        // Remove multiple spaces and trim
        $sanitized = preg_replace('/\s+/', ' ', $sanitized);
        $sanitized = trim($sanitized);

        // Ensure the name is not too long (Microsoft Graph has limits)
        if (strlen($sanitized) > 100) {
            $sanitized = substr($sanitized, 0, 97) . '...';
        }

        Log::info("🧹 Sanitized folder name: '{$displayName}' → '{$sanitized}'");

        return $sanitized;
    }

    /**
     * Extract folder type from display name (TO or CC)
     */
    public static function extractFolderType(string $displayName): string
    {
        // First try with parentheses (new format)
        if (str_contains($displayName, '(TO)')) {
            return 'TO';
        } elseif (str_contains($displayName, '(CC)')) {
            return 'CC';
        }

        // Then try without parentheses, but ensure it's at the end (old format)
        if (preg_match('/\bTO\s*$/', $displayName)) {
            return 'TO';
        } elseif (preg_match('/\bCC\s*$/', $displayName)) {
            return 'CC';
        }

        return 'UNKNOWN';
    }

    /**
     * Generate a consistent folder display name
     */
    public static function generateFolderDisplayName($model, string $modelType, string $folderType): string
    {
        $title = self::getModelTitle($model);
        return "{$title} ({$folderType})";
    }

    /**
     * Validate email address
     */
    public static function isValidEmail(?string $email): bool
    {
        return !empty($email) && filter_var($email, FILTER_VALIDATE_EMAIL);
    }

    /**
     * Format user display name for contact
     */
    public static function formatUserDisplayName($user): string
    {
        $parts = [];

        if (!empty($user->first_name)) {
            $parts[] = $user->first_name;
        }

        if (!empty($user->last_name)) {
            $parts[] = $user->last_name;
        }

        if (empty($parts) && !empty($user->name)) {
            return $user->name;
        }

        return implode(' ', $parts) ?: 'Unknown User';
    }

    /**
     * Create contact data array for Microsoft Graph API
     */
    public static function createContactData($user, string $folderType): array
    {
        $displayName = self::formatUserDisplayName($user);

        $contactData = [
            'displayName' => $displayName,
            'givenName' => $user->name ?? '',
            'surname' => $user->last_name ?? '',
        ];

        // Add email addresses if available
        $emailAddresses = [];
        if (self::isValidEmail($user->email)) {
            $emailAddresses[] = [
                'address' => $user->email,
                'name' => $displayName
            ];
        }

        if (!empty($emailAddresses)) {
            $contactData['emailAddresses'] = $emailAddresses;
        }

        return $contactData;
    }

    /**
     * Log operation with consistent formatting
     */
    public static function logOperation(string $operation, string $message, array $context = []): void
    {
        $emoji = match($operation) {
            'create' => '➕',
            'update' => '✏️',
            'delete' => '🗑️',
            'sync' => '🔄',
            'info' => 'ℹ️',
            'warning' => '⚠️',
            'error' => '❌',
            'success' => '✅',
            default => '📝'
        };

        Log::info("{$emoji} {$message}", $context);
    }
}
