<?php

namespace Core\System\Updates;

use Core\System\License\LicenseClient;

class UpdateCenterService
{
    public function all(): array
    {
        $items = (new InstalledItemsService())->all();
        $result = [];
        foreach ($items as $item) {
            $result[] = $this->checkItem($item);
        }
        return $result;
    }

    public function checkIdentifier(string $identifier): ?array
    {
        $item = (new InstalledItemsService())->find($identifier);
        return $item ? $this->checkItem($item) : null;
    }

    private function checkItem(array $item): array
    {
        $client = new LicenseClient();
        $licenseKey = trim((string)($item['license_key'] ?? ''));

        if ($licenseKey === '') {
            return $item + [
                'status' => 'missing_license',
                'status_label' => 'Missing License',
                'update_available' => false,
                'latest_version' => $item['current_version'] ?? null,
                'notes' => '',
                'download_url' => null,
                'package_size' => null,
                'checksum' => null,
            ];
        }

        $res = $client->checkUpdateItem(
            (string)$item['product'],
            (string)$item['current_version'],
            $licenseKey,
            $item['kind'] === 'plugin' ? (string)$item['plugin_slug'] : null
        );

        return $item + [
            'status' => (string)($res['status'] ?? 'unknown'),
            'status_label' => (string)($res['message'] ?? ($res['status'] ?? 'unknown')),
            'update_available' => !empty($res['update_available']) || !empty($res['has_update']),
            'latest_version' => (string)($res['latest_version'] ?? $item['current_version']),
            'notes' => (string)($res['notes'] ?? $res['changelog'] ?? ''),
            'download_url' => $res['download_url'] ?? $res['download_endpoint'] ?? null,
            'package_size' => isset($res['package_size']) ? (int)$res['package_size'] : null,
            'checksum' => $res['checksum'] ?? null,
        ];
    }
}
