<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Models\HostSystemUpdateExecution;
use App\Services\SupportCenter\HostSystemUpdateMigrationBatchProcessRunner;
use App\Services\SupportCenter\HostSystemUpdateMigrationBatchRunner;
use Illuminate\Console\Command;
use Throwable;

final class DberpSystemUpdateMigrateBatchCommand extends Command
{
    protected $signature = 'dberp:update-migrate-batch {--execution= : 系统更新执行编号}';

    protected $description = '在独立 PHP CLI 进程中执行一个受控系统更新迁移批次';

    public function handle(HostSystemUpdateMigrationBatchRunner $runner): int
    {
        $executionNo = trim((string) $this->option('execution'));
        $execution = HostSystemUpdateExecution::query()->where('execution_no', $executionNo)->first();

        if (! $execution instanceof HostSystemUpdateExecution) {
            $this->error('System update execution not found.');

            return self::FAILURE;
        }

        try {
            $result = $runner->runNextBatch($execution->fresh(['package']) ?? $execution);
            $this->line(HostSystemUpdateMigrationBatchProcessRunner::RESULT_PREFIX.json_encode([
                'stage_completed' => $result->stageCompleted,
                'progress' => $result->progress->toArray(),
                'executed' => $result->executedMigrationNames,
            ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));

            return self::SUCCESS;
        } catch (Throwable $throwable) {
            report($throwable);
            $this->error($throwable->getMessage());

            return self::FAILURE;
        }
    }
}
