<?php
declare(strict_types=1);

namespace PpPhp\Core\Assets;

final class AssetResourcePackage
{
    public function __construct(
        private readonly string $id,
        private readonly string $label,
        private readonly string $type,
        private readonly string $version,
        private readonly array $assets = [],
        private readonly array $metadata = [],
        private readonly string $path = ''
    ) {}

    public static function fromResource(array $resource): self
    {
        return new self(
            (string) ($resource['id'] ?? ''),
            (string) ($resource['label'] ?? $resource['id'] ?? ''),
            (string) ($resource['type'] ?? 'asset'),
            (string) ($resource['version'] ?? '1.0.0'),
            (array) ($resource['assets'] ?? []),
            (array) ($resource['metadata'] ?? []),
            (string) ($resource['path'] ?? '')
        );
    }

    public function id(): string { return $this->id; }
    public function type(): string { return $this->type; }

    public function toAssetPackage(): AssetPackage
    {
        $package = new AssetPackage($this->id, $this->label, $this->version);

        foreach ((array) ($this->assets['css'] ?? []) as $index => $path) {
            $package->addCss((string) $path, [], 100 + (int) $index);
        }
        foreach ((array) ($this->assets['js'] ?? []) as $index => $path) {
            $package->addJs((string) $path, 'footer', [], 100 + (int) $index);
        }
        foreach ((array) ($this->assets['fonts'] ?? []) as $index => $path) {
            $package->assets->add(Asset::font((string) $path, [], 100 + (int) $index));
        }
        foreach ((array) ($this->assets['images'] ?? []) as $index => $path) {
            $package->assets->add(Asset::image((string) $path, [], 100 + (int) $index));
        }
        foreach ((array) ($this->assets['svg'] ?? []) as $index => $path) {
            $package->assets->add(Asset::svg((string) $path, [], 100 + (int) $index));
        }
        foreach ((array) ($this->assets['vendor'] ?? []) as $index => $path) {
            $package->assets->add(Asset::vendor((string) $path, 'footer', [], 100 + (int) $index));
        }

        return $package;
    }

    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'label' => $this->label,
            'type' => $this->type,
            'version' => $this->version,
            'assets' => $this->assets,
            'metadata' => $this->metadata,
            'path' => $this->path,
        ];
    }
}
