<?php

declare(strict_types=1);

namespace App\Services\Install;

use DomainException;
use Throwable;

final class WebInstallFailureClassifier
{
    public function toUserFacingException(Throwable $exception, WebInstallPhaseTracker $phaseTracker): Throwable
    {
        if ($exception instanceof DatabaseNotInstallableException
            || $exception instanceof WebInstallFinalizationIncompleteException
            || $exception instanceof DomainException) {
            return $exception;
        }

        if ($phaseTracker->hasReached(WebInstallPhase::RunningOptionalFinalizers)) {
            return new WebInstallFinalizationIncompleteException(
                message: WebInstallUserMessages::INSTALL_COMPLETED_WITH_FINALIZATION_WARNINGS,
                previous: $exception,
            );
        }

        if ($phaseTracker->hasReached(WebInstallPhase::Migrating)) {
            return new WebInstallFinalizationIncompleteException(previous: $exception);
        }

        return $exception;
    }
}
