<?php

declare(strict_types=1);

namespace KupShop\ComponentsBundle\Attributes;

#[\Attribute(\Attribute::TARGET_CLASS)]
class Component
{
    public function __construct(
        protected int $latestVersion = 1,
        /** @var Version[] */
        protected array $versions = [],
        protected string $entrypoint = 'app',
    ) {
        end($versions)->setIsLatest();
    }

    public function getVersions(): \Generator
    {
        $latestVersions = ['template' => 1, 'js' => 1, 'css' => 1];

        yield 1 => $latestVersions;

        foreach ($this->versions as $version) {
            if ($version->isNewTemplate()) {
                $latestVersions['template'] = $version->getVersionFrom();
            }

            if ($version->isNewJs()) {
                $latestVersions['js'] = $version->getVersionFrom();
            } elseif ($version->isNewJs() === null) {
                $latestVersions['js'] = 0;
            }

            if ($version->isNewCss()) {
                $latestVersions['css'] = $version->getVersionFrom();
            } elseif ($version->isNewCss() === null) {
                $latestVersions['css'] = 0;
            }

            yield $version->getVersionFrom() => $latestVersions;
        }
    }

    public function getConfig(): array
    {
        return [
            'versions' => iterator_to_array($this->getVersions()),
            'latestVersion' => $this->latestVersion,
            'entrypoint' => $this->entrypoint,
        ];
    }
}
