<?php

declare(strict_types=1);

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

namespace App\Services\SupportCenter;

use App\Models\HostSystemUpdateCheck;
use App\Models\HostSystemUpdateExecution;
use App\Models\HostSystemUpdatePackage;
use App\Support\DberpProductVersion;
use Throwable;

/**
 * 系统更新成功并写入版本后，将检查快照同步为「已是最新」（不发起远端 check）。
 */
final class HostSystemUpdateCheckSnapshotAfterUpdateService
{
    public function __construct(
        private readonly DberpProductVersion $productVersion,
        private readonly HostSystemUpdateNotificationSyncService $notificationSyncService,
    ) {}

    public function apply(HostSystemUpdateExecution $execution): void
    {
        $execution = $execution->fresh(['package']) ?? $execution;

        $currentDisplay = trim($this->productVersion->displayVersion());
        $currentUpdate = $this->productVersion->updateVersion();

        [$latestDisplay, $latestUpdate] = $this->resolveLatestVersions($execution, $currentDisplay, $currentUpdate);

        $record = HostSystemUpdateCheck::singleton();
        $record->fill([
            'current_version' => $currentDisplay !== '' ? $currentDisplay : $record->current_version,
            'current_update_version' => $currentUpdate,
            'latest_version' => $latestDisplay,
            'latest_update_version' => $latestUpdate,
            'update_available' => false,
        ]);
        $record->save();

        try {
            $this->notificationSyncService->sync($record->fresh() ?? $record);
        } catch (Throwable $exception) {
            report($exception);
        }
    }

    /**
     * @return array{0: string, 1: int}
     */
    private function resolveLatestVersions(
        HostSystemUpdateExecution $execution,
        string $currentDisplay,
        int $currentUpdate,
    ): array {
        $package = $execution->package;

        if ($package instanceof HostSystemUpdatePackage) {
            $packageVersion = trim((string) ($package->version ?? ''));

            if ($packageVersion !== '') {
                return [$packageVersion, $currentUpdate];
            }
        }

        return [$currentDisplay !== '' ? $currentDisplay : (string) ($execution->to_version ?? ''), $currentUpdate];
    }
}
