<?php

declare(strict_types=1);

namespace App\Framework\Encryption;

use App\Framework\Random\RandomGenerator;
use RuntimeException;

/**
 * Factory for creating encryption instances
 */
final readonly class EncryptionFactory
{
    public function __construct(
        private RandomGenerator $randomGenerator
    ) {
    }

    /**
     * Create the best available encryption method
     */
    public function createBest(string $encryptionKey): EncryptionInterface
    {
        if (extension_loaded('openssl')) {
            return new AesEncryption($this->randomGenerator, $encryptionKey);
        }

        // Fallback to basic encryption with warning
        error_log('[WARNING] OpenSSL not available, using BasicEncryption (NOT secure for production!)');

        return new BasicEncryption($this->randomGenerator, $encryptionKey);
    }

    /**
     * Create specific encryption method
     */
    public function create(string $method, string $encryptionKey): EncryptionInterface
    {
        return match (strtoupper($method)) {
            'AES', 'AES-256-CBC' => new AesEncryption($this->randomGenerator, $encryptionKey),
            'BASIC', 'BASIC-XOR' => new BasicEncryption($this->randomGenerator, $encryptionKey),
            default => throw new RuntimeException("Unsupported encryption method: {$method}")
        };
    }

    /**
     * Get available encryption methods
     */
    public function getAvailableMethods(): array
    {
        $methods = ['BASIC'];

        if (extension_loaded('openssl')) {
            $methods[] = 'AES';
        }

        return $methods;
    }

    /**
     * Check if a method is available
     */
    public function isMethodAvailable(string $method): bool
    {
        return in_array(strtoupper($method), $this->getAvailableMethods(), true);
    }

    /**
     * Get recommended method for current environment
     */
    public function getRecommendedMethod(): string
    {
        return extension_loaded('openssl') ? 'AES' : 'BASIC';
    }
}
