<?php

declare(strict_types=1);

namespace App\Entity;

use App\Enum\TokenType;
use App\Repository\TokenRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Uid\Uuid;

#[ORM\Entity(repositoryClass: TokenRepository::class)]
class Token
{
    #[ORM\Id]
    #[ORM\Column(length: 36)]
    private string $uuid;

    #[ORM\Column(enumType: TokenType::class)]
    private TokenType $type;

    #[ORM\ManyToOne]
    #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
    private Image $image;

    #[ORM\ManyToOne]
    #[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')]
    private ?User $recipientUser;

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

    #[ORM\Column]
    private \DateTimeImmutable $expiresAt;

    #[ORM\Column(nullable: true)]
    private ?\DateTimeImmutable $usedAt = null;

    public function __construct(
        TokenType $type,
        Image $image,
        ?User $recipientUser,
        ?string $recipientEmail,
        int $ttlDays,
    ) {
        $this->uuid          = Uuid::v4()->toRfc4122();
        $this->type          = $type;
        $this->image         = $image;
        $this->recipientUser = $recipientUser;
        $this->recipientEmail = $recipientEmail;
        $this->expiresAt     = new \DateTimeImmutable('+' . $ttlDays . ' days');
    }

    public function getUuid(): string { return $this->uuid; }
    public function getType(): TokenType { return $this->type; }
    public function getImage(): Image { return $this->image; }
    public function getRecipientUser(): ?User { return $this->recipientUser; }
    public function getRecipientEmail(): ?string { return $this->recipientEmail; }
    public function getExpiresAt(): \DateTimeImmutable { return $this->expiresAt; }
    public function getUsedAt(): ?\DateTimeImmutable { return $this->usedAt; }

    public function isValid(): bool
    {
        return $this->usedAt === null && $this->expiresAt > new \DateTimeImmutable();
    }

    public function consume(): void
    {
        $this->usedAt = new \DateTimeImmutable();
    }
}
