<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Remote\Entity\Provider;

use FiloBlu\Refilo\Helper\CatalogProductData;
use FiloBlu\Refilo\Remote\Entity\AbstractEntity;
use FiloBlu\Refilo\Remote\Entity\EntityInterface;
use FiloBlu\Refilo\Remote\Entity\UrlRewrite;
use FiloBlu\Refilo\Remote\Entity\UrlRewriteFactory;
use Magento\Framework\DB\Select;

/**
 *
 */
class DisabledProductUrlProvider extends AbstractUrlProvider
{

    /**
     * @return Select
     */
    public function getSelect(): Select
    {
        $connection = $this->getResourceConnection()->getConnection();
        $urlRewriteTable = $connection->getTableName('url_rewrite');
        $storeTable = $connection->getTableName('store');

        if (!$this->getUrlHelper()->isRedirectCatalogProductEnabled()) {
            return $connection->select()
                ->from($urlRewriteTable)
                ->where('FALSE');
        }

        $storeCondition = '!=0';

        if ($this->hasStore()) {
            $storeId = $this->getStore()->getId();
            $storeCondition = "= $storeId";
        }

        $disabledEntityIds = $this->getDisabledEntityFilter()->getIds($this->getStore());

        if (empty($disabledEntityIds)) {
            return $connection->select()
                ->from($urlRewriteTable)
                ->where('FALSE');
        }

        $select = $connection->select()
            ->from(
                [
                    'u' => $urlRewriteTable
                ],
                [
                    AbstractEntity::ID     => 'u.url_rewrite_id',
                    UrlRewrite::URL_ID     => 'u.url_rewrite_id',
                    UrlRewrite::ENTITY_ID  => 'u.entity_id',
                    UrlRewrite::URL        => 'u.request_path',
                    UrlRewrite::TARGET_URL => 'u.target_path'
                ]
            )->joinInner(
                [
                    's' => $storeTable
                ],
                "s.store_id = u.store_id AND u.store_id $storeCondition AND entity_type = 'product'",
                [
                    UrlRewrite::STORE => 's.code'
                ]
            );

        if (!empty($this->ids)) {
            $select->where(
                'u.url_rewrite_id IN (?)',
                $this->ids
            );
        }

        $select->where('u.entity_id IN (?)', $disabledEntityIds);
        $select->order('u.target_path ASC');

        return $select;
    }

    /**
     * @param array $row
     * @return \FiloBlu\Refilo\Remote\Entity\EntityInterface
     */
    public function adapt(array $row): EntityInterface
    {
        /** @var UrlRewrite $urlRewrite */
        $urlRewrite = $this->getUrlRewriteFactory()->create(['data' => $row]);

        // This 2 following setting are mandatory to Refilo / BlueHeadless to perfom redirect
        $urlRewrite->setType(null);
        $urlRewrite->setIsRedirect('301');

        // Since it is a redirect set values to null/empty
        $urlRewrite->setHreflang([]);
        $urlRewrite->setCanonical();
        $urlRewrite->setBreadcrumbs([]);

        // Set target path
        $categoryId = $this->getUrlHelper()->getCategoryByProductId($row['entity_id']);
        $storeId = 0;
        if ($this->hasStore()) {
            $storeId = $this->getStore()->getId();
        }
        $urlRewrite->setTargetUrl($this->getUrlHelper()->getCategoryUrl($categoryId, $storeId));
        return $urlRewrite;
    }
}
