<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Marketing;

use CpCreation\VitiCore\Marketing\Model\ProductReview;

final readonly class ReviewPublicationPolicy
{
    public const int MAX_PUBLICATION_DELAY_DAYS = 30;
    public const int PUBLIC_RETENTION_YEARS = 5;
    public const int REVIEW_DATA_RETENTION_YEARS = 5;
    public const int UNUSED_INVITATION_GRACE_DAYS = 30;

    public function publicationDeadline(ProductReview $review): \DateTimeImmutable
    {
        return $review->getSubmittedAt()->add(
            new \DateInterval(sprintf('P%dD', self::MAX_PUBLICATION_DELAY_DAYS)),
        );
    }

    public function publicSince(?\DateTimeImmutable $now = null): \DateTimeImmutable
    {
        return ($now ?? new \DateTimeImmutable())->sub(
            new \DateInterval(sprintf('P%dY', self::PUBLIC_RETENTION_YEARS)),
        );
    }

    public function retainedReviewDataSince(?\DateTimeImmutable $now = null): \DateTimeImmutable
    {
        return ($now ?? new \DateTimeImmutable())->sub(
            new \DateInterval(sprintf('P%dY', self::REVIEW_DATA_RETENTION_YEARS)),
        );
    }

    public function unusedInvitationPurgeBefore(?\DateTimeImmutable $now = null): \DateTimeImmutable
    {
        return ($now ?? new \DateTimeImmutable())->sub(
            new \DateInterval(sprintf('P%dD', self::UNUSED_INVITATION_GRACE_DAYS)),
        );
    }

    public function isPublic(ProductReview $review, ?\DateTimeImmutable $now = null): bool
    {
        if (ProductReview::STATUS_PUBLISHED !== $review->getStatus()) {
            return false;
        }

        $publishedAt = $review->getPublishedAt();
        if (null === $publishedAt) {
            return false;
        }

        $now ??= new \DateTimeImmutable();

        return $publishedAt >= $this->publicSince($now) && $publishedAt <= $now;
    }
}
