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

use CpCreation\VitiCore\Behavior\HasTimestamp;
use CpCreation\VitiCore\Behavior\Impl\Timestamp;
use CpCreation\VitiCore\TransactionalEmail\Repository\TransactionalEmailQueueRepository;
use Doctrine\ORM\Mapping as ORM;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;

#[ORM\Entity(repositoryClass: TransactionalEmailQueueRepository::class)]
#[ORM\Table(name: 'transactional_email_queue')]
#[ORM\UniqueConstraint(name: 'uniq_transactional_email_queue_source', columns: ['transactional_email_id', 'related_type', 'related_id'])]
#[ORM\Index(name: 'idx_transactional_email_queue_due', columns: ['scheduled_at', 'sent_at', 'skipped_at', 'failed_at'])]
#[ORM\HasLifecycleCallbacks]
class TransactionalEmailQueue implements HasTimestamp
{
    use Timestamp;

    public const string RELATED_TYPE_CART = 'cart';

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

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

    #[ORM\Column(length: 64)]
    private string $triggerEvent;

    #[ORM\Column(length: 64)]
    private string $relatedType;

    #[ORM\Column(length: 64)]
    private string $relatedId;

    #[ORM\Column(length: 255, nullable: true)]
    private ?string $recipientEmail = null;

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

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

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

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

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

    /**
     * @var array<string, scalar|null>
     */
    #[ORM\Column(type: 'json', nullable: true)]
    private ?array $context = null;

    /**
     * @param array<string, scalar|null> $context
     */
    public function __construct(
        TransactionalEmail $transactionalEmail,
        string $triggerEvent,
        string $relatedType,
        string $relatedId,
        ?string $recipientEmail,
        \DateTimeImmutable $scheduledAt,
        array $context = [],
    ) {
        $this->id = Uuid::uuid4();
        $this->transactionalEmail = $transactionalEmail;
        $this->triggerEvent = $triggerEvent;
        $this->relatedType = $relatedType;
        $this->relatedId = $relatedId;
        $this->recipientEmail = $recipientEmail;
        $this->scheduledAt = $scheduledAt;
        $this->context = [] !== $context ? $context : null;
    }

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

    public function getTransactionalEmail(): TransactionalEmail
    {
        return $this->transactionalEmail;
    }

    public function getTriggerEvent(): string
    {
        return $this->triggerEvent;
    }

    public function getRelatedType(): string
    {
        return $this->relatedType;
    }

    public function getRelatedId(): string
    {
        return $this->relatedId;
    }

    public function getRecipientEmail(): ?string
    {
        return $this->recipientEmail;
    }

    public function getScheduledAt(): \DateTimeImmutable
    {
        return $this->scheduledAt;
    }

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

    public function markSent(?\DateTimeImmutable $sentAt = null): void
    {
        $this->sentAt = $sentAt ?? new \DateTimeImmutable();
        $this->failedAt = null;
        $this->errorMessage = null;
    }

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

    public function markSkipped(?string $reason = null): void
    {
        $this->skippedAt = new \DateTimeImmutable();
        $this->errorMessage = $reason;
    }

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

    public function markFailed(string $errorMessage): void
    {
        $this->failedAt = new \DateTimeImmutable();
        $this->errorMessage = $errorMessage;
    }

    public function getErrorMessage(): ?string
    {
        return $this->errorMessage;
    }

    /**
     * @return array<string, scalar|null>
     */
    public function getContext(): array
    {
        return $this->context ?? [];
    }
}
