<?php

namespace KupShop\GraphQLBundle\ApiAdmin\Types\User;

use KupShop\GraphQLBundle\ApiAdmin\Annotation\Module;
use KupShop\GraphQLBundle\ApiShared\Types\PriceLevel\PriceLevel;
use KupShop\GraphQLBundle\ApiShared\Types\PriceList\PriceList;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\PricelistBundle\Util\PriceListWorker;
use TheCodingMachine\GraphQLite\Annotations\Field;
use TheCodingMachine\GraphQLite\Annotations\Type;

/**
 * Skupina uživatelů.
 */
#[Type]
class UserGroup
{
    public function __construct(
        private readonly array $group,
    ) {
    }

    #[Field(description: 'ID')]
    public function getId(): int
    {
        return (int) $this->group['id'];
    }

    #[Field(description: 'Název skupiny')]
    public function getName(): string
    {
        return $this->group['name'];
    }

    #[Field(description: 'Popis')]
    public function getDescription(): ?string
    {
        return $this->group['descr'];
    }

    /**
     * @return string[]|null
     */
    #[Field(description: 'Typy skupiny')]
    public function getTypes(): ?array
    {
        if (empty($this->group['types'])) {
            return null;
        }

        return explode(',', $this->group['types']);
    }

    #[Field(description: 'Cenová hladina')]
    #[Module(\Modules::PRICE_LEVELS)]
    public function getPriceLevel(): ?PriceLevel
    {
        static $priceLevels = [];

        if ($this->group['id_price_level'] ?? false) {
            if (!isset($priceLevels[$this->group['id_price_level']])) {
                $priceLevelService = ServiceContainer::getService(\KupShop\CatalogBundle\PriceLevel::class);
                $priceLevels[$this->group['id_price_level']] = new PriceLevel(
                    $priceLevelService->createFromDB($this->group['id_price_level']));
            }

            return $priceLevels[$this->group['id_price_level']];
        }

        return null;
    }

    #[Field(description: 'Ceník')]
    #[Module(\Modules::PRICELISTS)]
    public function getPriceList(): ?PriceList
    {
        if ($this->group['id_pricelist'] ?? false) {
            $priceListWorker = ServiceContainer::getService(PriceListWorker::class);
            if ($priceList = $priceListWorker->getPriceList((int) $this->group['id_pricelist'])) {
                return new PriceList($priceList);
            }
        }

        return null;
    }
}
