<?php

namespace App\Services\Certification;

/*
|--------------------------------------------------------------------------
| Workflow Certification Engine
|--------------------------------------------------------------------------
|
| Legacy Workflow Certification Engine.
| This engine executes WorkflowStateValidator instances only.
| It MUST NOT depend on the Enterprise Certification framework.
|
|--------------------------------------------------------------------------
*/

class CertificationEngine
{
    private array $validators = [];

    public function __construct()
    {
        $this->validators[] =
            new WorkflowStateValidator();
    }

    public function run(?int $conferenceId = null): array
    {
        $results = [];

        foreach ($this->validators as $validator) {

            $results[] =
                $validator->validate(
                    $conferenceId
                );

        }

        return [

            'results' =>
                $results,

            'summary' =>
                $this->summary($results)

        ];
    }

    private function summary(array $results): array
    {
        $checked = 0;
        $critical = 0;
        $warning = 0;
        $scoreTotal = 0;

        foreach ($results as $result) {

            $checked +=
                (int)$result->checked;

            $critical +=
                $result->criticalCount();

            $warning +=
                $result->warningCount();

            $scoreTotal +=
                $result->score();

        }

        $count =
            max(
                1,
                count($results)
            );

        $score =
            (int)round(
                $scoreTotal / $count
            );

        return [

            'checked' =>
                $checked,

            'critical' =>
                $critical,

            'warning' =>
                $warning,

            'score' =>
                $score,

            'status' =>
                $critical > 0
                    ? 'critical'
                    : (
                        $warning > 0
                            ? 'warning'
                            : 'healthy'
                    )

        ];
    }
}
