<?php

namespace App\Services;

use App\Models\LicenseVerificationLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class LicenseVerificationLogger
{
    /**
     * Log license verification attempt
     */
    public static function log(
        string $purchaseCode,
        string $domain,
        bool $isValid,
        string $message,
        ?array $responseData = null,
        string $source = 'install',
        ?Request $request = null,
        ?string $errorDetails = null
    ): LicenseVerificationLog {
        try {
            // Get request information
            $ipAddress = $request ? $request->ip() : request()->ip();
            $userAgent = $request ? $request->userAgent() : request()->userAgent();
            
            // Hash the purchase code for security
            $purchaseCodeHash = md5($purchaseCode);
            
            // Determine status
            $status = $isValid ? 'success' : 'failed';
            if ($errorDetails) {
                $status = 'error';
            }
            
            // Create log entry
            $log = LicenseVerificationLog::create([
                'purchase_code_hash' => $purchaseCodeHash,
                'domain' => $domain,
                'ip_address' => $ipAddress,
                'user_agent' => $userAgent,
                'is_valid' => $isValid,
                'response_message' => $message,
                'response_data' => $responseData,
                'verification_source' => $source,
                'status' => $status,
                'error_details' => $errorDetails,
                'verified_at' => $isValid ? now() : null
            ]);
            
            // Log to Laravel log file for additional tracking
            $logLevel = $isValid ? 'info' : 'warning';
            Log::channel('single')->$logLevel('License verification attempt', [
                'purchase_code_hash' => $purchaseCodeHash,
                'domain' => $domain,
                'ip_address' => $ipAddress,
                'is_valid' => $isValid,
                'status' => $status,
                'source' => $source,
                'message' => $message
            ]);
            
            return $log;
            
        } catch (\Exception $e) {
            // Fallback logging if database fails
            Log::error('Failed to log license verification attempt', [
                'purchase_code_hash' => md5($purchaseCode),
                'domain' => $domain,
                'error' => $e->getMessage()
            ]);
            
            // Return a mock log entry
            return new LicenseVerificationLog([
                'purchase_code_hash' => md5($purchaseCode),
                'domain' => $domain,
                'is_valid' => $isValid,
                'response_message' => $message,
                'status' => $isValid ? 'success' : 'failed'
            ]);
        }
    }
    
    /**
     * Get verification statistics
     */
    public static function getStats(int $days = 30): array
    {
        $startDate = now()->subDays($days);
        
        return [
            'total_attempts' => LicenseVerificationLog::where('created_at', '>=', $startDate)->count(),
            'successful_attempts' => LicenseVerificationLog::where('created_at', '>=', $startDate)->successful()->count(),
            'failed_attempts' => LicenseVerificationLog::where('created_at', '>=', $startDate)->failed()->count(),
            'unique_domains' => LicenseVerificationLog::where('created_at', '>=', $startDate)->distinct('domain')->count('domain'),
            'unique_ips' => LicenseVerificationLog::where('created_at', '>=', $startDate)->distinct('ip_address')->count('ip_address'),
            'recent_failed_attempts' => LicenseVerificationLog::recent(24)->failed()->count(),
        ];
    }
    
    /**
     * Get suspicious activity (multiple failed attempts from same IP)
     */
    public static function getSuspiciousActivity(int $hours = 24, int $minAttempts = 5): array
    {
        return LicenseVerificationLog::recent($hours)
            ->failed()
            ->selectRaw('ip_address, COUNT(*) as attempt_count, MAX(created_at) as last_attempt')
            ->groupBy('ip_address')
            ->having('attempt_count', '>=', $minAttempts)
            ->orderBy('attempt_count', 'desc')
            ->get()
            ->toArray();
    }
    
    /**
     * Get recent verification attempts
     */
    public static function getRecentAttempts(int $limit = 50): \Illuminate\Database\Eloquent\Collection
    {
        return LicenseVerificationLog::with([])
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get();
    }
    
    /**
     * Clean old logs (older than specified days)
     */
    public static function cleanOldLogs(int $days = 90): int
    {
        $cutoffDate = now()->subDays($days);
        return LicenseVerificationLog::where('created_at', '<', $cutoffDate)->delete();
    }
}
