<?php

declare(strict_types=1);

/**
 * Hydrate promo-rule extension attributes when sales rules are loaded.
 */

namespace Autogedal\PromoRules\Plugin\SalesRule\Model;

use Autogedal\PromoRules\Api\RuleConfigRepositoryInterface;
use Autogedal\PromoRules\Model\Rule\DiscountScope;
use Magento\SalesRule\Api\Data\RuleExtensionFactory;
use Magento\SalesRule\Api\Data\RuleInterface;
use Magento\SalesRule\Model\RuleRepository;

/**
 * Handles read access to promo-rule extension attributes.
 */
class RuleRepositoryPlugin
{
    /**
     * @param RuleConfigRepositoryInterface $ruleConfigRepository
     * @param RuleExtensionFactory $ruleExtensionFactory
     */
    public function __construct(
        private readonly RuleConfigRepositoryInterface $ruleConfigRepository,
        private readonly RuleExtensionFactory $ruleExtensionFactory
    ) {
    }

    /**
     * Hydrate the rule extension attributes after loading by ID.
     *
     * @param RuleRepository $subject
     * @param RuleInterface $result
     * @return RuleInterface
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function afterGetById(RuleRepository $subject, RuleInterface $result): RuleInterface
    {
        $extensionAttributes = $result->getExtensionAttributes() ?: $this->ruleExtensionFactory->create();
        $extensionAttributes->setUsesPerEmail(0);
        $extensionAttributes->setBlockDiscountScope(DiscountScope::NONE);
        $result->setExtensionAttributes($extensionAttributes);

        $ruleId = (int) $result->getRuleId();
        if ($ruleId <= 0) {
            return $result;
        }

        try {
            $ruleConfig = $this->ruleConfigRepository->getByRuleId($ruleId);
        } catch (\Throwable) {
            return $result;
        }

        $extensionAttributes->setUsesPerEmail($ruleConfig->getUsesPerEmail());
        $extensionAttributes->setBlockDiscountScope($ruleConfig->getBlockDiscountScope());

        return $result;
    }
}
