<?php

declare(strict_types=1);

namespace App\Application\Admin\Infrastructure;

use App\Application\Admin\Service\AdminLayoutProcessor;
use App\Framework\Attributes\Route;
use App\Framework\Auth\Auth;
use App\Framework\DateTime\Clock;
use App\Framework\Http\Method;
use App\Framework\Meta\MetaData;
use App\Framework\Redis\Services\RedisMonitoringService;
use App\Framework\Router\Result\ViewResult;

final readonly class RedisController
{
    public function __construct(
        private RedisMonitoringService $redisMonitoring,
        private Clock $clock,
        private AdminLayoutProcessor $layoutProcessor,
    ) {
    }

    #[Auth]
    #[Route(path: '/admin/infrastructure/redis', method: Method::GET, name: 'admin.infrastructure.redis')]
    public function show(): ViewResult
    {
        try {
            $basicInfo = $this->redisMonitoring->getBasicInfo();
            $databases = $this->redisMonitoring->getDatabases();
            $cachePatterns = $this->redisMonitoring->analyzeCachePatterns();
            $keyDetails = $this->redisMonitoring->getKeyDetails(20);
            $slowLog = $this->redisMonitoring->getSlowLog(10);
            $connectionInfo = $this->redisMonitoring->getConnectionPoolInfo();

            // Filter non-empty cache patterns
            $nonEmptyPatterns = array_filter($cachePatterns, fn ($pattern) => ! $pattern->isEmpty());

            $redisData = [
                'basic_info' => $basicInfo,
                'databases' => $databases,
                'cache_patterns' => $nonEmptyPatterns,
                'key_details' => $keyDetails,
                'slow_log' => $slowLog,
                'connection_info' => $connectionInfo,
                'status' => 'Connected',
                'is_connected' => true,
                'has_error' => false,
                'has_basic_info' => true,
                'has_databases' => count($databases) > 0,
                'has_cache_patterns' => count($nonEmptyPatterns) > 0,
                'has_key_details' => count($keyDetails) > 0,
                'has_slow_log' => count($slowLog) > 0,
            ];
        } catch (\Throwable $e) {
            error_log("RedisController: Exception caught: " . $e->getMessage());
            error_log("RedisController: Exception trace: " . $e->getTraceAsString());
            $redisData = [
                'status' => 'Error: ' . $e->getMessage(),
                'basic_info' => null,
                'databases' => [],
                'cache_patterns' => [],
                'key_details' => [],
                'slow_log' => [],
                'connection_info' => null,
                'is_connected' => false,
                'has_error' => true,
                'has_basic_info' => false,
                'has_databases' => false,
                'has_cache_patterns' => false,
                'has_key_details' => false,
                'has_slow_log' => false,
            ];
        }

        error_log("RedisController: redisData has_error: " . ($redisData['has_error'] ? 'true' : 'false'));
        error_log("RedisController: redisData has_basic_info: " . ($redisData['has_basic_info'] ? 'true' : 'false'));
        error_log("RedisController: redisData status: " . $redisData['status']);

        $data = [
            'title' => 'Redis Dashboard',
            'redis' => $redisData,
            'current_year' => $this->clock->now()->format('Y'),
        ];

        $finalData = $this->layoutProcessor->processLayoutFromArray($data);

        return new ViewResult(
            template: 'redis',
            metaData: new MetaData('Redis Dashboard', 'Redis monitoring and cache analysis'),
            data: $finalData
        );
    }
}
