<?php

declare(strict_types=1);

namespace Autogedal\PromoRules\Model;

use Autogedal\PromoRules\Api\Data\RuleConfigInterface;
use Autogedal\PromoRules\Api\RuleConfigRepositoryInterface;
use Autogedal\PromoRules\Model\ResourceModel\RuleConfig as RuleConfigResource;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\NoSuchEntityException;

/**
 * Default repository for promo-rule configuration persistence.
 */
class RuleConfigRepository implements RuleConfigRepositoryInterface
{
    public function __construct(
        private readonly RuleConfigResource $resource,
        private readonly RuleConfigFactory $ruleConfigFactory
    ) {
    }

    public function save(RuleConfigInterface $ruleConfig): RuleConfigInterface
    {
        try {
            $this->resource->save($ruleConfig);
        } catch (\Throwable $exception) {
            throw new CouldNotSaveException(
                __('Unable to save promo rule config.'),
                $exception
            );
        }

        return $ruleConfig;
    }

    public function getByRuleId(int $ruleId): RuleConfigInterface
    {
        $ruleConfig = $this->ruleConfigFactory->create();
        $this->resource->load($ruleConfig, $ruleId, RuleConfigInterface::RULE_ID);

        if ($ruleConfig->getConfigId() === null) {
            throw new NoSuchEntityException(
                __('Promo rule config not found for rule ID %1.', $ruleId)
            );
        }

        return $ruleConfig;
    }

    public function delete(RuleConfigInterface $ruleConfig): bool
    {
        try {
            $this->resource->delete($ruleConfig);
        } catch (\Throwable $exception) {
            throw new CouldNotDeleteException(
                __('Unable to delete promo rule config.'),
                $exception
            );
        }

        return true;
    }

    public function deleteById(int $configId): bool
    {
        $ruleConfig = $this->ruleConfigFactory->create();
        $this->resource->load($ruleConfig, $configId);

        if ($ruleConfig->getConfigId() === null) {
            throw new NoSuchEntityException(
                __('Promo rule config not found for config ID %1.', $configId)
            );
        }

        return $this->delete($ruleConfig);
    }
}
