<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\HumanTask;

final class HumanTaskAssignment
{
    public function __construct(
        private readonly string $assignmentId,
        private readonly string $taskId,
        private readonly string $assignee,
        private readonly string $action,
        private readonly bool $successful,
        private readonly string $message = '',
        private readonly string $createdAt = ''
    ) {}

    public static function create(string $taskId, string $assignee, string $action, bool $successful, string $message = ''): self
    {
        return new self(
            'human_assignment_' . substr(hash('sha256', $taskId . $assignee . $action . microtime(true)), 0, 24),
            $taskId,
            $assignee,
            $action,
            $successful,
            $message,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['assignmentId'] ?? ''),
            (string) ($data['taskId'] ?? ''),
            (string) ($data['assignee'] ?? ''),
            (string) ($data['action'] ?? ''),
            (bool) ($data['successful'] ?? false),
            (string) ($data['message'] ?? ''),
            (string) ($data['createdAt'] ?? '')
        );
    }

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

    public function toArray(): array
    {
        return [
            'assignmentId' => $this->assignmentId,
            'taskId' => $this->taskId,
            'assignee' => $this->assignee,
            'action' => $this->action,
            'successful' => $this->successful,
            'message' => $this->message,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
