<?php

declare(strict_types=1);

namespace App\Exceptions\SupportCenter;

use RuntimeException;

/**
 * 更新回滚或恢复失败（不含密钥与 .env 内容）。
 */
final class HostSystemUpdateRecoveryException extends RuntimeException
{
    public function __construct(
        private readonly string $userFacingMessage,
        private readonly string $errorCode,
        ?\Throwable $previous = null,
    ) {
        parent::__construct($userFacingMessage, 0, $previous);
    }

    public function userFacingMessage(): string
    {
        return $this->userFacingMessage;
    }

    public function errorCode(): string
    {
        return $this->errorCode;
    }

    public static function rollbackNotAllowed(string $status): self
    {
        return new self(
            userFacingMessage: (string) __('dberp.system_update.recovery.rollback_not_allowed', ['status' => $status]),
            errorCode: 'recovery_rollback_not_allowed',
        );
    }

    public static function backupUnavailable(): self
    {
        return new self(
            userFacingMessage: (string) __('dberp.system_update.recovery.backup_unavailable'),
            errorCode: 'recovery_backup_unavailable',
        );
    }

    public static function fileRestoreFailed(string $reason): self
    {
        return new self(
            userFacingMessage: (string) __('dberp.system_update.recovery.file_restore_failed', ['reason' => $reason]),
            errorCode: 'recovery_file_restore_failed',
        );
    }

    public static function envRestoreFailed(string $reason): self
    {
        return new self(
            userFacingMessage: (string) __('dberp.system_update.recovery.env_restore_failed', ['reason' => $reason]),
            errorCode: 'recovery_env_restore_failed',
        );
    }

    public static function maintenanceCommandFailed(string $command, int $exitCode): self
    {
        $message = $command === 'up'
            ? (string) __('dberp.system_update.recovery.maintenance_up_failed_detail', [
                'exit_code' => (string) $exitCode,
            ])
            : (string) __('dberp.system_update.recovery.maintenance_command_failed', [
                'command' => $command,
                'exit_code' => (string) $exitCode,
            ]);

        return new self(
            userFacingMessage: $message,
            errorCode: 'recovery_maintenance_command_failed',
        );
    }
}
