<?php

namespace KupShop\ComponentsBundle\Twig\Components\Product\VariationLabel;

use KupShop\ComponentsBundle\Attributes\Component;
use KupShop\ComponentsBundle\Attributes\Version;
use KupShop\ComponentsBundle\Entity\Thumbnail;
use KupShop\ComponentsBundle\Twig\Components\Product\VariationLabel;
use KupShop\ContentBundle\Util\ImageLocator;
use KupShop\KupShopBundle\Context\UserContext;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent(template: '@Components/components/Product/VariationLabel/ColorCatalog/ColorCatalog.1.html.twig')]
#[Component(2, [
    new Version(1, newJs: null),
    new Version(2, newTemplate: true, newJs: true, newCss: true),
])]
class ColorCatalog extends VariationLabel
{
    public string $kind = 'O';
    public string $image_type = 'product_catalog';
    public string $image_type_small = 'product_gallery_thumb';
    public bool $showPhotoInsteadOfColor = false;

    public function __construct(
        private readonly TranslatorInterface $translator,
        private readonly UserContext $userContext,
        private readonly ImageLocator $imageLocator,
    ) {
        parent::__construct($this->translator, $this->userContext);
    }

    public function getVariationThumbnailByKind(int $idVariation, string $type, ?string $kind = null): ?string
    {
        $config = $this->imageLocator->getConfig();
        $size = array_search($type, $config['id_to_type']);

        $this->multiFetch()->fetchPhotos($size, false);

        $kindExists = $kind && in_array($kind, array_column($this->product->photos, 'show_in_lead'));
        $photos = array_filter(
            $this->product->photos,
            fn ($photo) => $kindExists ? $photo['show_in_lead'] === $kind and $photo['id_variation'] === $idVariation : $photo['id_variation'] === $idVariation
        );

        $photo = reset($photos);
        if (!$photo) {
            return null;
        }

        $thumbnail = new Thumbnail((string) $photo['id'], $photo['descr'], (string) $photo['date_update']);
        $settings = $this->imageLocator->getTypeConfig($type);
        $imageTypeSizeKey = array_key_first($settings['sizes']);

        return $this->imageLocator->getThumbnailUrl($thumbnail, $type, $imageTypeSizeKey);
    }
}
