<?php

declare(strict_types=1);

namespace App\Services\SupportCenter;

/**
 * 系统更新迁移分批进度（写入 step session，面向 UI 百分比）。
 */
final readonly class HostSystemUpdateMigrationProgress
{
    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;
        }

        return (int) min(100, max(0, (int) round(($progress->completed / $progress->total) * 100)));
    }

    /**
     * @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'] ?? 5)),
        );
    }

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