<?php

declare(strict_types=1);

namespace App\Framework\Health;

final readonly class HealthReport
{
    public function __construct(
        public HealthStatus $overallStatus,
        // Todo: HealthCheckResult ...$results
        public array $results // HealthCheckResult[]
    ) {
    }

    public function isHealthy(): bool
    {
        return $this->overallStatus === HealthStatus::HEALTHY;
    }

    public function hasWarnings(): bool
    {
        return $this->overallStatus === HealthStatus::WARNING;
    }

    public function isUnhealthy(): bool
    {
        return $this->overallStatus === HealthStatus::UNHEALTHY;
    }

    public function getFailedChecks(): array
    {
        return array_filter(
            $this->results,
            fn (HealthCheckResult $result) => $result->isUnhealthy()
        );
    }

    public function getWarningChecks(): array
    {
        return array_filter(
            $this->results,
            fn (HealthCheckResult $result) => $result->isWarning()
        );
    }

    public function getHealthyChecks(): array
    {
        return array_filter(
            $this->results,
            fn (HealthCheckResult $result) => $result->isHealthy()
        );
    }

    public function toArray(): array
    {
        $categorized = [];

        foreach ($this->results as $name => $result) {
            $categorized[] = [
                'name' => $name,
                'result' => $result->toArray(),
            ];
        }

        return [
            'overall_status' => $this->overallStatus->value,
            'overall_icon' => $this->overallStatus->getIcon(),
            'overall_color' => $this->overallStatus->getColor(),
            'summary' => [
                'total_checks' => count($this->results),
                'healthy_count' => count($this->getHealthyChecks()),
                'warning_count' => count($this->getWarningChecks()),
                'unhealthy_count' => count($this->getFailedChecks()),
            ],
            'checks' => $categorized,
            'timestamp' => time(),
        ];
    }

    public function getSummary(): string
    {
        $total = count($this->results);
        $healthy = count($this->getHealthyChecks());
        $warnings = count($this->getWarningChecks());
        $failed = count($this->getFailedChecks());

        if ($failed > 0) {
            return "{$failed} failed, {$warnings} warnings, {$healthy} healthy out of {$total} checks";
        }

        if ($warnings > 0) {
            return "{$warnings} warnings, {$healthy} healthy out of {$total} checks";
        }

        return "All {$total} checks are healthy";
    }
}
