<?php

declare(strict_types=1);

namespace PpPhp\Core\Maintenance\Results;

final class MaintenanceReport
{
    /**
     * @var MaintenanceResult[]
     */
    private array $results = [];

    public function add(MaintenanceResult $result): void
    {
        $this->results[] = $result;
    }

    /**
     * @return MaintenanceResult[]
     */
    public function results(): array
    {
        return $this->results;
    }

    public function errorCount(): int
    {
        return array_sum(array_map(
            static fn (MaintenanceResult $result): int => $result->errorCount(),
            $this->results
        ));
    }

    public function warningCount(): int
    {
        return array_sum(array_map(
            static fn (MaintenanceResult $result): int => $result->warningCount(),
            $this->results
        ));
    }

    public function totalIssues(): int
    {
        return array_sum(array_map(
            static fn (MaintenanceResult $result): int => count($result->issues()),
            $this->results
        ));
    }

    public function healthScore(): int
    {
        $penalty = ($this->errorCount() * 10) + ($this->warningCount() * 3);

        return max(0, min(100, 100 - $penalty));
    }

    public function toArray(): array
    {
        return [
            'healthScore' => $this->healthScore(),
            'errors' => $this->errorCount(),
            'warnings' => $this->warningCount(),
            'totalIssues' => $this->totalIssues(),
            'results' => array_map(
                static fn (MaintenanceResult $result): array => $result->toArray(),
                $this->results
            ),
        ];
    }
}
