<?php
declare(strict_types=1);

namespace Autogedal\Manufacturers\Model\ResourceModel;

use Autogedal\Manufacturers\Api\Data\ManufacturerPageInterface;
use Magento\Cms\Api\Data\PageInterface;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class ManufacturerPage extends AbstractDb
{
    public const MAIN_TABLE = 'autogedal_manufacturer_pages';

    protected function _construct(): void
    {
        $this->_init(self::MAIN_TABLE, ManufacturerPageInterface::PAGE_ID);
    }

    public function getCmsPageIds(?int $optionId = null): array
    {
        $connection = $this->getConnection();
        $select = $connection->select()
            ->from(['manufacturer_page' => $this->getMainTable()], [])
            ->join(
                ['cms_page' => $this->getTable('cms_page')],
                'cms_page.' . PageInterface::IDENTIFIER . ' = manufacturer_page.' . ManufacturerPageInterface::CMS_PAGE,
                [PageInterface::PAGE_ID]
            );

        if ($optionId !== null) {
            $select->where('manufacturer_page.' . ManufacturerPageInterface::OPTION_ID . ' = ?', $optionId);
        }

        return array_map('intval', $connection->fetchCol($select));
    }
}
