<?php

declare(strict_types=1);

namespace App\Framework\MagicLinks;

use App\Framework\MagicLinks\ValueObjects\MagicLinkPayload;
use DateTimeImmutable;

final readonly class MagicLinkData
{
    public function __construct(
        public string             $id,
        public TokenAction        $action,
        public MagicLinkPayload   $payload,
        public DateTimeImmutable  $expiresAt,
        public DateTimeImmutable  $createdAt,
        public bool               $oneTimeUse = false,
        public ?string            $createdByIp = null,
        public ?string            $userAgent = null,
        public bool $isUsed = false,
        public ?DateTimeImmutable $usedAt = null
    ) {
    }

    public function isExpired(): bool
    {
        return $this->expiresAt <= new DateTimeImmutable();
    }

    public function isValid(): bool
    {
        return ! $this->isExpired() && (! $this->oneTimeUse || ! $this->isUsed);
    }

    public function getRemainingTime(): \DateInterval
    {
        $now = new DateTimeImmutable();
        if ($this->isExpired()) {
            return new \DateInterval('P0D');
        }

        return $now->diff($this->expiresAt);
    }

    public function withUsed(DateTimeImmutable $usedAt): self
    {
        return new self(
            id: $this->id,
            action: $this->action,
            payload: $this->payload,
            expiresAt: $this->expiresAt,
            createdAt: $this->createdAt,
            oneTimeUse: $this->oneTimeUse,
            createdByIp: $this->createdByIp,
            userAgent: $this->userAgent,
            isUsed: true,
            usedAt: $usedAt
        );
    }
}
