<?php

declare(strict_types=1);

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