<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Timer;

final class WorkflowTimerResult
{
    public function __construct(
        private readonly string $resultId,
        private readonly string $timerId,
        private readonly string $workflowInstanceId,
        private readonly string $activityId,
        private readonly bool $fired,
        private readonly string $message = '',
        private readonly string $createdAt = ''
    ) {}

    public static function createFired(WorkflowTimer $timer): self
    {
        return new self(
            'workflow_timer_result_' . substr(hash('sha256', $timer->timerId() . 'fired'), 0, 24),
            $timer->timerId(),
            $timer->workflowInstanceId(),
            $timer->activityId(),
            true,
            'timer fired',
            date('c')
        );
    }

    public static function skipped(WorkflowTimer $timer, string $message = 'timer not due'): self
    {
        return new self(
            'workflow_timer_result_' . substr(hash('sha256', $timer->timerId() . $message), 0, 24),
            $timer->timerId(),
            $timer->workflowInstanceId(),
            $timer->activityId(),
            false,
            $message,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['resultId'] ?? ''),
            (string) ($data['timerId'] ?? ''),
            (string) ($data['workflowInstanceId'] ?? ''),
            (string) ($data['activityId'] ?? ''),
            (bool) ($data['fired'] ?? false),
            (string) ($data['message'] ?? ''),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function isFired(): bool
    {
        return $this->fired;
    }

    public function toArray(): array
    {
        return [
            'resultId' => $this->resultId,
            'timerId' => $this->timerId,
            'workflowInstanceId' => $this->workflowInstanceId,
            'activityId' => $this->activityId,
            'fired' => $this->isFired(),
            'message' => $this->message,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
