<?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\Model;

use CpCreation\VitiCore\Behavior\HasTimestamp;
use CpCreation\VitiCore\Behavior\Impl\Timestamp;
use CpCreation\VitiCore\Cart\Model\CartItem;
use CpCreation\VitiCore\Marketing\Repository\ProductReviewRepository;
use CpCreation\VitiCore\Product\Model\Product;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
use Symfony\Component\Validator\Constraints as Assert;

#[ORM\Entity(repositoryClass: ProductReviewRepository::class)]
#[ORM\Table(name: 'marketing_product_review')]
#[ORM\UniqueConstraint(name: 'uniq_marketing_product_review_invitation_product', columns: ['invitation_id', 'product_id'])]
#[ORM\Index(name: 'marketing_product_review_status_idx', columns: ['status'])]
#[ORM\Index(name: 'marketing_product_review_product_idx', columns: ['product_id'])]
#[ORM\HasLifecycleCallbacks]
class ProductReview implements HasTimestamp
{
    use Timestamp;

    public const string STATUS_PENDING = 'pending';
    public const string STATUS_PUBLISHED = 'published';
    public const string STATUS_REJECTED = 'rejected';
    public const string STATUS_WITHDRAWN = 'withdrawn';

    public const string MODERATION_REASON_ILLEGAL = 'illegal';
    public const string MODERATION_REASON_PERSONAL_DATA = 'personal_data';
    public const string MODERATION_REASON_OFF_TOPIC = 'off_topic';
    public const string MODERATION_REASON_SPAM = 'spam';
    public const string MODERATION_REASON_FRAUD = 'fraud';
    public const string MODERATION_REASON_INCOMPREHENSIBLE = 'incomprehensible';

    #[ORM\Id]
    #[ORM\Column(type: 'uuid')]
    #[ORM\GeneratedValue(strategy: 'NONE')]
    private UuidInterface $id;

    #[ORM\ManyToOne(targetEntity: ReviewInvitation::class)]
    #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
    private ReviewInvitation $invitation;

    #[ORM\ManyToOne(targetEntity: Product::class)]
    #[ORM\JoinColumn(nullable: false)]
    private Product $product;

    #[ORM\ManyToOne(targetEntity: CartItem::class)]
    #[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')]
    private ?CartItem $cartItem;

    #[Assert\Range(min: 1, max: 5)]
    #[ORM\Column(type: 'smallint')]
    private int $rating;

    #[Assert\Length(min: 2, max: 80)]
    #[ORM\Column(type: 'string', length: 80)]
    private string $authorDisplayName;

    #[Assert\Length(max: 120)]
    #[ORM\Column(type: 'string', length: 120, nullable: true)]
    private ?string $title;

    #[Assert\Length(min: 3, max: 5000)]
    #[ORM\Column(type: 'text')]
    private string $comment;

    #[ORM\Column(type: 'string', length: 24)]
    private string $status;

    #[ORM\Column(name: 'experience_at', type: 'datetime_immutable')]
    private \DateTimeImmutable $purchasedAt;

    #[ORM\Column(type: 'datetime_immutable')]
    private \DateTimeImmutable $submittedAt;

    #[ORM\Column(type: 'datetime_immutable', nullable: true)]
    private ?\DateTimeImmutable $publishedAt = null;

    #[ORM\Column(type: 'datetime_immutable', nullable: true)]
    private ?\DateTimeImmutable $rejectedAt = null;

    #[ORM\Column(type: 'string', length: 64, nullable: true)]
    private ?string $rejectionReasonCode = null;

    #[ORM\Column(type: 'text', nullable: true)]
    private ?string $rejectionReason = null;

    #[ORM\Column(type: 'datetime_immutable', nullable: true)]
    private ?\DateTimeImmutable $withdrawnAt = null;

    #[ORM\Column(type: 'string', length: 64, nullable: true)]
    private ?string $withdrawalReasonCode = null;

    #[ORM\Column(type: 'text', nullable: true)]
    private ?string $withdrawalReason = null;

    #[ORM\Column(type: 'text', nullable: true)]
    private ?string $merchantReply = null;

    /** @var Collection<int, ProductReviewModerationAction> */
    #[ORM\OneToMany(
        targetEntity: ProductReviewModerationAction::class,
        mappedBy: 'review',
        cascade: ['persist'],
        orphanRemoval: true,
    )]
    #[ORM\OrderBy(['occurredAt' => 'DESC'])]
    private Collection $moderationActions;

    public function __construct(
        ReviewInvitation $invitation,
        Product $product,
        ?CartItem $cartItem,
        int $rating,
        string $authorDisplayName,
        ?string $title,
        string $comment,
        bool $moderationRequired,
        ?\DateTimeImmutable $submittedAt = null,
    ) {
        $this->id = Uuid::uuid4();
        $this->moderationActions = new ArrayCollection();
        $this->invitation = $invitation;
        $this->product = $product;
        $this->cartItem = $cartItem;
        $this->rating = $rating;
        $this->authorDisplayName = mb_trim($authorDisplayName);
        $this->title = null !== $title && '' !== mb_trim($title) ? mb_trim($title) : null;
        $this->comment = mb_trim($comment);
        $this->submittedAt = $submittedAt ?? new \DateTimeImmutable();
        $paidAt = $invitation->getCart()->getCartCheckout()?->getPayedAt();
        $this->purchasedAt = null !== $paidAt
            ? \DateTimeImmutable::createFromInterface($paidAt)
            : $invitation->getCart()->getFulfilledAt() ?? $this->submittedAt;
        $this->status = $moderationRequired ? self::STATUS_PENDING : self::STATUS_PUBLISHED;
        $this->publishedAt = $moderationRequired ? null : $this->submittedAt;
    }

    public function getId(): UuidInterface
    {
        return $this->id;
    }

    public function getInvitation(): ReviewInvitation
    {
        return $this->invitation;
    }

    public function getProduct(): Product
    {
        return $this->product;
    }

    public function getCartItem(): ?CartItem
    {
        return $this->cartItem;
    }

    public function getRating(): int
    {
        return $this->rating;
    }

    public function getAuthorDisplayName(): string
    {
        return $this->authorDisplayName;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function getComment(): string
    {
        return $this->comment;
    }

    public function getStatus(): string
    {
        return $this->status;
    }

    public function getExperienceAt(): \DateTimeImmutable
    {
        return $this->purchasedAt;
    }

    public function getPurchasedAt(): \DateTimeImmutable
    {
        return $this->purchasedAt;
    }

    public function getSubmittedAt(): \DateTimeImmutable
    {
        return $this->submittedAt;
    }

    public function getPublishedAt(): ?\DateTimeImmutable
    {
        return $this->publishedAt;
    }

    public function getRejectedAt(): ?\DateTimeImmutable
    {
        return $this->rejectedAt;
    }

    public function getRejectionReason(): ?string
    {
        return $this->rejectionReason;
    }

    public function getRejectionReasonCode(): ?string
    {
        return $this->rejectionReasonCode;
    }

    public function getWithdrawnAt(): ?\DateTimeImmutable
    {
        return $this->withdrawnAt;
    }

    public function getWithdrawalReason(): ?string
    {
        return $this->withdrawalReason;
    }

    public function getWithdrawalReasonCode(): ?string
    {
        return $this->withdrawalReasonCode;
    }

    public function getMerchantReply(): ?string
    {
        return $this->merchantReply;
    }

    /** @return Collection<int, ProductReviewModerationAction> */
    public function getModerationActions(): Collection
    {
        return $this->moderationActions;
    }

    /** @return list<string> */
    public static function getAllowedModerationReasonCodes(): array
    {
        return [
            self::MODERATION_REASON_ILLEGAL,
            self::MODERATION_REASON_PERSONAL_DATA,
            self::MODERATION_REASON_OFF_TOPIC,
            self::MODERATION_REASON_SPAM,
            self::MODERATION_REASON_FRAUD,
            self::MODERATION_REASON_INCOMPREHENSIBLE,
        ];
    }

    public function publish(?\DateTimeImmutable $publishedAt = null): void
    {
        $this->status = self::STATUS_PUBLISHED;
        $this->publishedAt = $publishedAt ?? new \DateTimeImmutable();
        $this->rejectedAt = null;
        $this->rejectionReasonCode = null;
        $this->rejectionReason = null;
        $this->withdrawnAt = null;
        $this->withdrawalReasonCode = null;
        $this->withdrawalReason = null;
    }

    public function reject(
        string $reasonCode,
        ?string $reason = null,
        ?\DateTimeImmutable $rejectedAt = null,
    ): void {
        self::assertAllowedModerationReasonCode($reasonCode);
        $this->status = self::STATUS_REJECTED;
        $this->rejectedAt = $rejectedAt ?? new \DateTimeImmutable();
        $this->rejectionReasonCode = $reasonCode;
        $this->rejectionReason = self::normalizeOptionalText($reason);
        $this->publishedAt = null;
        $this->withdrawnAt = null;
        $this->withdrawalReasonCode = null;
        $this->withdrawalReason = null;
    }

    public function withdraw(
        string $reasonCode,
        ?string $reason = null,
        ?\DateTimeImmutable $withdrawnAt = null,
    ): void {
        if (self::STATUS_PUBLISHED !== $this->status) {
            throw new \DomainException('Seul un avis publié peut être retiré.');
        }

        self::assertAllowedModerationReasonCode($reasonCode);
        $this->status = self::STATUS_WITHDRAWN;
        $this->publishedAt = null;
        $this->withdrawnAt = $withdrawnAt ?? new \DateTimeImmutable();
        $this->withdrawalReasonCode = $reasonCode;
        $this->withdrawalReason = self::normalizeOptionalText($reason);
    }

    public function reply(?string $reply): void
    {
        $this->merchantReply = null !== $reply && '' !== mb_trim($reply) ? mb_trim($reply) : null;
    }

    public function resubmit(
        ?CartItem $cartItem,
        int $rating,
        string $authorDisplayName,
        ?string $title,
        string $comment,
        bool $moderationRequired,
        ?\DateTimeImmutable $submittedAt = null,
    ): void {
        if (self::STATUS_REJECTED !== $this->status) {
            throw new \DomainException('Seul un avis refusé peut être soumis à nouveau.');
        }

        $this->cartItem = $cartItem;
        $this->rating = $rating;
        $this->authorDisplayName = mb_trim($authorDisplayName);
        $this->title = self::normalizeOptionalText($title);
        $this->comment = mb_trim($comment);
        $this->submittedAt = $submittedAt ?? new \DateTimeImmutable();
        $this->status = $moderationRequired ? self::STATUS_PENDING : self::STATUS_PUBLISHED;
        $this->publishedAt = $moderationRequired ? null : $this->submittedAt;
        $this->rejectedAt = null;
        $this->rejectionReasonCode = null;
        $this->rejectionReason = null;
        $this->withdrawnAt = null;
        $this->withdrawalReasonCode = null;
        $this->withdrawalReason = null;
    }

    /** @return array<string, bool|int|string|null> */
    public function moderationSnapshot(): array
    {
        return [
            'status' => $this->status,
            'rating' => $this->rating,
            'title' => $this->title,
            'comment' => $this->comment,
            'merchant_reply' => $this->merchantReply,
            'rejection_reason_code' => $this->rejectionReasonCode,
            'rejection_reason' => $this->rejectionReason,
            'withdrawal_reason_code' => $this->withdrawalReasonCode,
            'withdrawal_reason' => $this->withdrawalReason,
        ];
    }

    public function addModerationAction(ProductReviewModerationAction $action): void
    {
        if (!$this->moderationActions->contains($action)) {
            $this->moderationActions->add($action);
        }
    }

    private static function assertAllowedModerationReasonCode(string $reasonCode): void
    {
        if (!\in_array($reasonCode, self::getAllowedModerationReasonCodes(), true)) {
            throw new \InvalidArgumentException(sprintf('Motif de modération inconnu : « %s ».', $reasonCode));
        }
    }

    private static function normalizeOptionalText(?string $text): ?string
    {
        if (null === $text || '' === mb_trim($text)) {
            return null;
        }

        return mb_trim($text);
    }
}
