<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Services\Install;

/**
 * Web 安装迁移阶段进度（写入 progress.json，面向业务展示与 API）。
 */
final readonly class WebInstallMigrationProgress
{
    public function __construct(
        public int $total,
        public int $completed,
        public int $pending,
        public ?string $current,
        public int $batchSize,
    ) {}

    public static function percentComplete(self $progress): int
    {
        if ($progress->total <= 0) {
            return 0;
        }

        $ratio = $progress->completed / $progress->total;

        return (int) min(100, max(0, (int) round($ratio * 100)));
    }

    public static function businessLabel(self $progress): string
    {
        if ($progress->total <= 0) {
            return '正在创建数据表';
        }

        return sprintf('正在创建数据表 · 已完成 %d%%', self::percentComplete($progress));
    }

    /**
     * @param  array<string, mixed>  $payload
     */
    public static function fromArray(array $payload): self
    {
        return new self(
            total: max(0, (int) ($payload['total'] ?? 0)),
            completed: max(0, (int) ($payload['completed'] ?? 0)),
            pending: max(0, (int) ($payload['pending'] ?? 0)),
            current: isset($payload['current']) && is_string($payload['current']) && $payload['current'] !== ''
                ? $payload['current']
                : null,
            batchSize: max(1, (int) ($payload['batch_size'] ?? 10)),
        );
    }

    /**
     * @return array{
     *     total: int,
     *     completed: int,
     *     pending: int,
     *     current: string|null,
     *     batch_size: int
     * }
     */
    public function toArray(): array
    {
        return [
            'total' => $this->total,
            'completed' => $this->completed,
            'pending' => $this->pending,
            'current' => $this->current,
            'batch_size' => $this->batchSize,
        ];
    }
}
