<?php

namespace App\Livewire\Concerns;

use App\Models\ProvisioningRun;

/**
 * Builds the {label, state} array a progress stepper renders from a run's
 * pipeline + current step + status. Shared by admin and customer views.
 */
trait BuildsRunSteps
{
    /** @return array<int, array{label: string, state: string}> */
    protected function buildRunSteps(?ProvisioningRun $run): array
    {
        if ($run === null) {
            return [];
        }

        $pipeline = config('provisioning.pipelines.'.$run->pipeline, []);
        $current = $run->current_step;
        $status = $run->status;

        $steps = [];
        foreach ($pipeline as $index => $class) {
            if ($status === ProvisioningRun::STATUS_COMPLETED || $index < $current) {
                $state = 'done';
            } elseif ($index === $current) {
                $state = $status === ProvisioningRun::STATUS_FAILED ? 'failed' : 'running';
            } else {
                $state = 'pending';
            }

            $steps[] = ['label' => __(app($class)->label()), 'state' => $state];
        }

        return $steps;
    }

    protected function currentStepLabel(ProvisioningRun $run): string
    {
        $pipeline = config('provisioning.pipelines.'.$run->pipeline, []);
        $class = $pipeline[$run->current_step] ?? null;

        return $class ? __(app($class)->label()) : '—';
    }

    protected function runState(ProvisioningRun $run): string
    {
        return match ($run->status) {
            ProvisioningRun::STATUS_COMPLETED => 'done',
            ProvisioningRun::STATUS_FAILED => 'failed',
            default => 'running',
        };
    }
}
