<?php

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiTheme\Twig;

use CpCreation\VitiCore\Contact\ContactProvider;
use CpCreation\VitiCore\Shop\Repository\ShopConfigRepository;
use CpCreation\VitiTheme\Theme\ThemeDefinition;
use CpCreation\VitiTheme\Theme\ThemeResolver;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

final class ThemeExtension extends AbstractExtension
{
    public function __construct(
        private readonly ThemeResolver $themeResolver,
        private readonly ShopConfigRepository $shopConfigRepository,
        private readonly ContactProvider $contactProvider,
    ) {}

    public function getFunctions(): array
    {
        return [
            new TwigFunction('viti_theme', $this->activeTheme(...)),
            new TwigFunction('viti_theme_config', $this->themeConfig(...)),
            new TwigFunction('viti_theme_asset', $this->themeAsset(...)),
            new TwigFunction('checkout_brand_image_path', $this->checkoutBrandImagePath(...)),
        ];
    }

    public function activeTheme(): ThemeDefinition
    {
        return $this->themeResolver->active();
    }

    public function themeConfig(?string $key = null): mixed
    {
        $metadata = $this->activeTheme()->metadata;

        if (null === $key) {
            return $metadata;
        }

        return $metadata[$key] ?? null;
    }

    public function themeAsset(string $path): string
    {
        return \sprintf(
            'themes/%s/%s',
            $this->activeTheme()->name,
            mb_ltrim($path, '/'),
        );
    }

    public function checkoutBrandImagePath(): ?string
    {
        return $this->shopConfigRepository->findOne()?->getImage()?->getPath()
            ?? $this->contactProvider->getContact()?->getImage()?->getPath();
    }
}
