<?php

declare(strict_types=1);

namespace App\Framework\Console\Health;

final readonly class HealthService
{
    /**
     * @param HealthCheck[] $healthChecks
     */
    public function __construct(
        private array $healthChecks
    ) {
    }

    public function runAllChecks(): HealthReport
    {
        $results = [];
        $overallStatus = HealthStatus::HEALTHY;

        foreach ($this->healthChecks as $check) {
            $result = $check->check();
            $results[$check->getName()] = $result;

            // Determine overall status
            if ($result->isUnhealthy() && $check->isRequired()) {
                $overallStatus = HealthStatus::UNHEALTHY;
            } elseif ($result->isWarning() && $overallStatus === HealthStatus::HEALTHY) {
                $overallStatus = HealthStatus::WARNING;
            }
        }

        return new HealthReport($overallStatus, $results);
    }

    public function runCheck(string $checkName): ?HealthCheckResult
    {
        foreach ($this->healthChecks as $check) {
            if ($check->getName() === $checkName) {
                return $check->check();
            }
        }

        return null;
    }

    public function getAvailableChecks(): array
    {
        return array_map(function (HealthCheck $check) {
            return [
                'name' => $check->getName(),
                'description' => $check->getDescription(),
                'required' => $check->isRequired(),
            ];
        }, $this->healthChecks);
    }

    public function runRequiredChecks(): HealthReport
    {
        $results = [];
        $overallStatus = HealthStatus::HEALTHY;

        foreach ($this->healthChecks as $check) {
            if (! $check->isRequired()) {
                continue;
            }

            $result = $check->check();
            $results[$check->getName()] = $result;

            if ($result->isUnhealthy()) {
                $overallStatus = HealthStatus::UNHEALTHY;
            } elseif ($result->isWarning() && $overallStatus === HealthStatus::HEALTHY) {
                $overallStatus = HealthStatus::WARNING;
            }
        }

        return new HealthReport($overallStatus, $results);
    }
}
