<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Services\SupportCenter\HostSystemUpdateAutoCheckTriggerService;
use App\Services\SupportCenter\HostSystemUpdateCheckService;
use Illuminate\Console\Command;
use Throwable;

/**
 * 可选：CLI 手动/计划任务触发官方更新检查（零配置提醒不依赖本命令）。
 */
final class DberpSystemUpdateCheckCommand extends Command
{
    protected $signature = 'dberp:system-update:check
                            {--force : 忽略自动检查节流间隔（仅 CLI）}';

    protected $description = '检查 DBErp 官方系统更新（写入本地快照并同步更新提醒）';

    public function handle(
        HostSystemUpdateCheckService $checkService,
        HostSystemUpdateAutoCheckTriggerService $autoCheckTrigger,
    ): int {
        if ($this->option('force')) {
            try {
                $check = $checkService->check();
                $this->info($check->update_available
                    ? '发现可用更新：'.($check->latest_version ?? '未知版本')
                    : '当前已是最新版本（以官方检查为准）。');

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

                return self::FAILURE;
            }
        }

        if (! $autoCheckTrigger->performImmediateCheck(ignoreThrottle: false)) {
            $this->warn('未执行检查：可能处于节流窗口、更新进行中、未接入官方或连通性不可用。');

            return self::FAILURE;
        }

        $this->info('官方更新检查已完成。');

        return self::SUCCESS;
    }
}
