<?php

declare(strict_types=1);

namespace PpPhp\Core\Platform\Services\Descriptor;

final class DescriptorFactory
{
    public static function service(array $data, string $source = ''): ServiceDescriptor
    {
        return new ServiceDescriptor(
            id: (string) ($data['id'] ?? ''),
            label: (string) ($data['label'] ?? $data['name'] ?? $data['id'] ?? ''),
            version: (string) ($data['version'] ?? '1.0.0'),
            type: (string) ($data['type'] ?? 'service'),
            description: (string) ($data['description'] ?? ''),
            dependencies: is_array($data['dependencies'] ?? null) ? $data['dependencies'] : [],
            capabilities: is_array($data['capabilities'] ?? null) ? $data['capabilities'] : [],
            aliases: is_array($data['aliases'] ?? null) ? $data['aliases'] : [],
            tags: is_array($data['tags'] ?? null) ? $data['tags'] : [],
            lifecycle: (string) ($data['lifecycle'] ?? 'singleton'),
            visibility: (string) ($data['visibility'] ?? 'public'),
            lazy: (bool) ($data['lazy'] ?? true),
            metadata: is_array($data['metadata'] ?? null) ? $data['metadata'] : [],
            source: $source
        );
    }

    /**
     * @return ServiceDescriptor[]
     */
    public static function fromManifest(array $manifest, string $source = ''): array
    {
        $services = is_array($manifest['services'] ?? null) ? $manifest['services'] : [];

        return array_values(array_map(
            static fn (array $service): ServiceDescriptor => self::service($service, $source),
            array_filter($services, static fn (mixed $service): bool => is_array($service))
        ));
    }
}
