<?php

declare(strict_types=1);

namespace App\Framework\Deployment\Pipeline\ValueObjects;

use App\Framework\Core\ValueObjects\Duration;

/**
 * Complete Pipeline Execution Result
 *
 * Aggregates all stage results and overall pipeline outcome.
 */
final readonly class PipelineResult
{
    /**
     * @param array<StageResult> $stageResults
     */
    public function __construct(
        public PipelineId $pipelineId,
        public DeploymentEnvironment $environment,
        public PipelineStatus $status,
        public Duration $totalDuration,
        public array $stageResults,
        public ?string $error = null
    ) {}

    public function isSuccess(): bool
    {
        return $this->status === PipelineStatus::SUCCESS;
    }

    public function isFailed(): bool
    {
        return $this->status === PipelineStatus::FAILED;
    }

    public function wasRolledBack(): bool
    {
        return $this->status === PipelineStatus::ROLLED_BACK;
    }

    /**
     * Get the failed stage (if any)
     */
    public function getFailedStage(): ?StageResult
    {
        foreach ($this->stageResults as $result) {
            if ($result->isFailed()) {
                return $result;
            }
        }
        return null;
    }

    /**
     * Get total number of completed stages
     */
    public function getCompletedStagesCount(): int
    {
        return count($this->stageResults);
    }

    /**
     * Get total number of successful stages
     */
    public function getSuccessfulStagesCount(): int
    {
        return count(array_filter(
            $this->stageResults,
            fn(StageResult $result) => $result->isSuccess()
        ));
    }
}
