<?php

declare(strict_types=1);

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,
        ];
    }
}
