<?php

declare(strict_types=1);

namespace App\Framework\Queue;

use App\Framework\Core\ValueObjects\Duration;
use App\Framework\Core\ValueObjects\Timestamp;

/**
 * Distributed Lock Value Object
 *
 * Repräsentiert einen verteilten Lock für Job-Koordination
 */
final readonly class DistributedLock
{
    public function __construct(
        public string $lockId,
        public string $jobId,
        public string $ownerId,
        public Timestamp $acquiredAt,
        public Timestamp $expiresAt,
        public ?Duration $ttl = null
    ) {
    }

    public function isExpired(Timestamp $now): bool
    {
        return $now->isAfter($this->expiresAt);
    }

    public function remainingTime(Timestamp $now): Duration
    {
        if ($this->isExpired($now)) {
            return Duration::fromSeconds(0);
        }

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

    public function toArray(): array
    {
        return [
            'lock_id' => $this->lockId,
            'job_id' => $this->jobId,
            'owner_id' => $this->ownerId,
            'acquired_at' => $this->acquiredAt->format('Y-m-d H:i:s'),
            'expires_at' => $this->expiresAt->format('Y-m-d H:i:s'),
            'ttl_seconds' => $this->ttl?->toSeconds(),
        ];
    }
}
