<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow;

final class WorkflowTask
{
    public function __construct(
        private readonly string $taskId,
        private readonly string $instanceId,
        private readonly string $activityId,
        private readonly string $type = 'system',
        private readonly string $status = 'pending',
        private readonly string $assignee = '',
        private readonly array $payload = [],
        private readonly string $createdAt = ''
    ) {}

    public static function create(WorkflowInstance $instance, WorkflowActivity $activity): self
    {
        $type = $activity->type() === 'human' ? 'human' : 'system';
        $config = $activity->config();

        return new self(
            'workflow_task_' . substr(hash('sha256', $instance->instanceId() . $activity->activityId()), 0, 24),
            $instance->instanceId(),
            $activity->activityId(),
            $type,
            'pending',
            (string) ($config['assignee'] ?? ''),
            $config,
            date('c')
        );
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['taskId'] ?? ''),
            (string) ($data['instanceId'] ?? ''),
            (string) ($data['activityId'] ?? ''),
            (string) ($data['type'] ?? 'system'),
            (string) ($data['status'] ?? 'pending'),
            (string) ($data['assignee'] ?? ''),
            (array) ($data['payload'] ?? []),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function taskId(): string { return $this->taskId; }
    public function instanceId(): string { return $this->instanceId; }
    public function activityId(): string { return $this->activityId; }
    public function status(): string { return $this->status; }

    public function complete(): self
    {
        return new self($this->taskId, $this->instanceId, $this->activityId, $this->type, 'completed', $this->assignee, $this->payload, $this->createdAt);
    }

    public function toArray(): array
    {
        return [
            'taskId' => $this->taskId,
            'instanceId' => $this->instanceId,
            'activityId' => $this->activityId,
            'type' => $this->type,
            'status' => $this->status,
            'assignee' => $this->assignee,
            'payload' => $this->payload,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
