<?php
/**
 * Copyright 2023 Adobe
 * All Rights Reserved.
 */
declare(strict_types=1);

namespace Magento\Sitemap\Model\ResourceModel\Catalog;

use Magento\CatalogUrlRewrite\Model\CategoryUrlRewriteGenerator;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Select;
use Magento\Store\Api\Data\StoreInterface;

class CategorySelectBuilder
{
    /**
     * @param ResourceConnection $resource
     */
    public function __construct(
        private readonly ResourceConnection $resource
    ) {
    }

    /**
     * Allow to modify a select statement with plugins
     *
     * @param string $mainTableName
     * @param string $idField
     * @param StoreInterface $store
     * @param string $path
     * @return Select
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function execute(string $mainTableName, string $idField, StoreInterface $store, string $path)
    {
        $connection = $this->resource->getConnection();

        return $connection->select()->from(
            ['e' => $mainTableName],
            [$idField, 'updated_at']
        )->joinLeft(
            ['url_rewrite' => $this->resource->getTableName('url_rewrite')],
            'e.entity_id = url_rewrite.entity_id AND url_rewrite.is_autogenerated = 1'
            . $connection->quoteInto(' AND url_rewrite.store_id = ?', $store->getId())
            . $connection->quoteInto(' AND url_rewrite.entity_type = ?', CategoryUrlRewriteGenerator::ENTITY_TYPE),
            ['url' => 'request_path']
        )->where(
            'e.path LIKE ?',
            $path . '/%'
        );
    }
}
