<?php

declare(strict_types=1);

namespace App\Exceptions\SupportCenter;

use RuntimeException;

/**
 * 更新包 manifest 读取或校验失败（面向用户的文案，不含密钥）。
 */
final class HostSystemUpdateManifestException 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 packageNotVerified(): self
    {
        return new self(
            userFacingMessage: (string) __('dberp.system_update.manifest.package_not_verified'),
            errorCode: 'manifest_package_not_verified',
        );
    }

    public static function packageFileMissing(): self
    {
        return new self(
            userFacingMessage: (string) __('dberp.system_update.manifest.package_file_missing'),
            errorCode: 'manifest_package_file_missing',
        );
    }

    public static function manifestMissing(): self
    {
        return new self(
            userFacingMessage: (string) __('dberp.system_update.manifest.manifest_missing'),
            errorCode: 'manifest_missing',
        );
    }

    public static function invalidJson(?\Throwable $previous = null): self
    {
        return new self(
            userFacingMessage: (string) __('dberp.system_update.manifest.invalid_json'),
            errorCode: 'manifest_invalid_json',
            previous: $previous,
        );
    }

    public static function zipOpenFailed(): self
    {
        return self::archiveOpenFailed();
    }

    public static function archiveOpenFailed(): self
    {
        return new self(
            userFacingMessage: (string) __('dberp.system_update.manifest.archive_open_failed'),
            errorCode: 'manifest_archive_open_failed',
        );
    }

    public static function unsupportedArchiveFormat(string $format): self
    {
        return new self(
            userFacingMessage: (string) __('dberp.system_update.manifest.unsupported_archive_format', [
                'format' => $format,
            ]),
            errorCode: 'manifest_unsupported_archive_format',
        );
    }

    public static function validationFailed(string $message, string $errorCode): self
    {
        return new self(
            userFacingMessage: $message,
            errorCode: $errorCode,
        );
    }
}
