<?php

declare(strict_types=1);

namespace EasyChat\Library\Android;

final class AndroidUpdatePolicy
{
    




    public function evaluate(array $release, array $devices): array
    {
        $latestCode = (int)($release['version_code'] ?? 0);
        $latestName = trim((string)($release['version_name'] ?? ''));
        $minimumCode = (int)($release['minimum_supported_version_code'] ?? 0);
        if ($latestCode <= 0 || $latestName === '') {
            return ['outdated' => [], 'known_total' => 0, 'critical' => false];
        }

        $known = 0;
        $outdated = [];
        $critical = false;
        foreach ($devices as $device) {
            $code = (int)($device['app_version_code'] ?? 0);
            $name = trim((string)($device['app_version_name'] ?? ''));
            if ($code <= 0 && !$this->isVersion($name)) {
                continue;
            }
            $known++;

            $needsUpdate = $code > 0
                ? $code < $latestCode
                : version_compare($name, $latestName, '<');
            if (!$needsUpdate) {
                continue;
            }

            $isCritical = $minimumCode > 0 && $code > 0 && $code < $minimumCode;
            $critical = $critical || $isCritical;
            $outdated[] = [
                'device_label' => trim((string)($device['device_label'] ?? '')) ?: 'Android',
                'current_version' => $name !== '' ? $name : ('code ' . $code),
                'version_code' => $code,
                'last_seen_at' => (string)($device['last_seen_at'] ?? ''),
                'critical' => $isCritical,
            ];
        }

        return [
            'outdated' => $outdated,
            'known_total' => $known,
            'critical' => $critical,
        ];
    }

    private function isVersion(string $value): bool
    {
        return preg_match('/^\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.]+)?$/D', $value) === 1;
    }
}
