<?php
declare(strict_types=1);

namespace Autogedal\Manufacturers\Block\Product;

use Autogedal\Manufacturers\Model\Config;
use Autogedal\Manufacturers\Model\ManufacturerPage;
use Autogedal\Manufacturers\Model\ManufacturerUrl;
use Autogedal\Manufacturers\Model\ResourceModel\ManufacturerPage as ManufacturerPageResource;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Cms\Model\Page as CmsPage;
use Magento\Framework\DataObject\IdentityInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;

class Manufacturer extends Template implements IdentityInterface
{
    private ?ProductInterface $currentProduct = null;

    public function __construct(
        Context $context,
        private readonly ManufacturerUrl $manufacturerUrl,
        private readonly Config $config,
        private readonly ProductRepositoryInterface $productRepository,
        private readonly ManufacturerPageResource $manufacturerPageResource,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }

    public function getProduct(): ?ProductInterface
    {
        if ($this->currentProduct !== null) {
            return $this->currentProduct;
        }

        $productId = (int)$this->getRequest()->getParam('id');
        if (!$productId) {
            return null;
        }

        try {
            $this->currentProduct = $this->productRepository->getById($productId);
        } catch (NoSuchEntityException) {
            return null;
        }

        return $this->currentProduct;
    }

    public function getManufacturerUrl(int|string $attributeValue): ?string
    {
        return $this->manufacturerUrl->getUrlByOptionId($attributeValue);
    }

    public function getManufacturerName(int|string $attributeValue): string
    {
        $attribute = $this->getProduct()?->getResource()->getAttribute($this->config->getProductAttribute());

        return $attribute && $attribute->usesSource()
            ? (string)$attribute->getSource()->getOptionText($attributeValue)
            : '';
    }

    public function getIdentities(): array
    {
        $optionId = (int)$this->getProduct()?->getData($this->config->getProductAttribute());
        if (!$optionId) {
            return [];
        }

        $identities = [ManufacturerPage::MANUFACTURER_CACHE_TAG . '_' . $optionId];
        foreach ($this->manufacturerPageResource->getCmsPageIds($optionId) as $cmsPageId) {
            $identities[] = CmsPage::CACHE_TAG . '_' . $cmsPageId;
        }

        return $identities;
    }
}
