<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Verification;

final class WorkflowFullRuntimeReport
{
    public function __construct(
        private readonly array $checks = [],
        private readonly array $statistics = [],
        private readonly string $status = 'PENDING',
        private readonly int $score = 0,
        private readonly string $createdAt = ''
    ) {}

    public static function fromChecks(array $checks): self
    {
        $rows = [];
        $passed = 0;

        foreach ($checks as $check) {
            $row = $check instanceof WorkflowFullRuntimeCheck ? $check->toArray() : (array) $check;
            $rows[] = $row;

            if (($row['passed'] ?? false) === true) {
                $passed++;
            }
        }

        $total = count($rows);
        $score = $total > 0 ? (int) round(($passed / $total) * 100) : 0;

        return new self(
            $rows,
            ['checks' => $total, 'passed' => $passed, 'failed' => $total - $passed],
            $score === 100 ? 'PASS' : 'FAIL',
            $score,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (array) ($data['checks'] ?? []),
            (array) ($data['statistics'] ?? []),
            (string) ($data['status'] ?? 'PENDING'),
            (int) ($data['score'] ?? 0),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function status(): string { return $this->status; }
    public function score(): int { return $this->score; }
    public function checks(): array { return $this->checks; }
    public function statistics(): array { return $this->statistics; }
    public function passed(): bool { return $this->status === 'PASS' && $this->score === 100; }

    public function toArray(): array
    {
        return [
            'status' => $this->status,
            'score' => $this->score,
            'checks' => $this->checks,
            'statistics' => $this->statistics,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
