<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Marketing;

use CpCreation\VitiCore\Marketing\Model\ProductReviewModerationAction;
use CpCreation\VitiCore\Marketing\Repository\ProductReviewRepository;

final readonly class DueProductReviewPublisher
{
    public function __construct(
        private ProductReviewRepository $reviewRepository,
        private ProductReviewHistoryRecorder $historyRecorder,
    ) {}

    public function publish(?\DateTimeImmutable $now = null): int
    {
        $now ??= new \DateTimeImmutable();
        $deadline = $now->sub(new \DateInterval(sprintf(
            'P%dD',
            ReviewPublicationPolicy::MAX_PUBLICATION_DELAY_DAYS,
        )));
        $reviews = $this->reviewRepository->findPendingSubmittedBefore($deadline);

        foreach ($reviews as $review) {
            $review->publish($now);
            $this->historyRecorder->record(
                review: $review,
                action: ProductReviewModerationAction::ACTION_PUBLISHED,
                actorIdentifier: 'system:publication-deadline',
                occurredAt: $now,
            );
            $this->reviewRepository->persist($review);
        }

        if ([] !== $reviews) {
            $this->reviewRepository->flush();
        }

        return \count($reviews);
    }
}
