<?php
declare(strict_types=1);

namespace Autogedal\Manufacturers\Model;

use Autogedal\Manufacturers\Api\Data\ManufacturerPageInterface;
use Autogedal\Manufacturers\Api\ManufacturerPageRepositoryInterface;
use Autogedal\Manufacturers\Model\ResourceModel\ManufacturerPage as ResourceModel;
use Autogedal\Manufacturers\Model\ResourceModel\ManufacturerPage\Collection;
use Autogedal\Manufacturers\Model\ResourceModel\ManufacturerPage\CollectionFactory;
use Magento\Framework\Api\SearchCriteria\CollectionProcessorInterface;
use Magento\Framework\Api\SearchCriteriaInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Phrase;

class ManufacturerPageRepository implements ManufacturerPageRepositoryInterface
{
    public function __construct(
        private readonly ResourceModel $resource,
        private readonly ManufacturerPageFactory $pageFactory,
        private readonly CollectionFactory $collectionFactory,
        private readonly CollectionProcessorInterface $collectionProcessor
    ) {
    }

    public function save(ManufacturerPageInterface $page): ManufacturerPageInterface
    {
        $this->resource->save($page);

        return $page;
    }

    public function getById($pageId): ManufacturerPageInterface
    {
        $page = $this->pageFactory->create();
        $this->resource->load($page, $pageId);
        if (!$page->getId()) {
            throw new NoSuchEntityException(__('The manufacturer page with ID "%1" doesn\'t exist.', $pageId));
        }

        return $page;
    }

    public function getByOptionId($optionId): ManufacturerPageInterface
    {
        return $this->getFirstBy(
            ManufacturerPageInterface::OPTION_ID,
            $optionId,
            __('The manufacturer page for option ID "%1" doesn\'t exist.', $optionId)
        );
    }

    public function getBySlug(string $slug): ManufacturerPageInterface
    {
        return $this->getFirstBy(
            ManufacturerPageInterface::SLUG,
            $slug,
            __('The manufacturer page with slug "%1" doesn\'t exist.', $slug)
        );
    }

    public function getList(SearchCriteriaInterface $searchCriteria): Collection
    {
        $collection = $this->collectionFactory->create();
        $this->collectionProcessor->process($searchCriteria, $collection);

        return $collection;
    }

    public function delete(ManufacturerPageInterface $page): bool
    {
        $this->resource->delete($page);

        return true;
    }

    public function deleteById($pageId): bool
    {
        return $this->delete($this->getById($pageId));
    }

    private function getFirstBy(string $field, mixed $value, Phrase $notFoundMessage): ManufacturerPageInterface
    {
        $page = $this->collectionFactory->create()->addFieldToFilter($field, $value)->getFirstItem();
        if (!$page->getId()) {
            throw new NoSuchEntityException($notFoundMessage);
        }

        return $page;
    }
}
