<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Distributed\Scheduler;

final class DistributedScheduleJob
{
    public function __construct(
        private readonly string $jobId,
        private readonly string $queueName,
        private readonly int $priority = 0,
        private readonly array $affinity = [],
        private readonly array $payload = [],
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $jobId, string $queueName, int $priority = 0, array $affinity = [], array $payload = []): self
    {
        return new self($jobId, $queueName, $priority, $affinity, $payload, date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['jobId'] ?? ''),
            (string) ($data['queueName'] ?? 'default'),
            (int) ($data['priority'] ?? 0),
            (array) ($data['affinity'] ?? []),
            (array) ($data['payload'] ?? []),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function jobId(): string { return $this->jobId; }
    public function queueName(): string { return $this->queueName; }
    public function priority(): int { return $this->priority; }
    public function affinity(): array { return $this->affinity; }

    public function toArray(): array
    {
        return [
            'jobId' => $this->jobId,
            'queueName' => $this->queueName,
            'priority' => $this->priority,
            'affinity' => $this->affinity,
            'payload' => $this->payload,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
