<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Workflow\Engine;

final class WorkflowGateway
{
    public const EXCLUSIVE = 'exclusive';
    public const PARALLEL = 'parallel';
    public const INCLUSIVE = 'inclusive';

    public function __construct(
        private readonly string $gatewayId,
        private readonly string $type,
        private readonly array $branches = [],
        private readonly string $joinActivityId = '',
        private readonly string $createdAt = ''
    ) {}

    public static function exclusive(string $gatewayId, array $branches): self
    {
        return new self($gatewayId, self::EXCLUSIVE, $branches, '', date('c'));
    }

    public static function parallel(string $gatewayId, array $branches, string $joinActivityId = ''): self
    {
        return new self($gatewayId, self::PARALLEL, $branches, $joinActivityId, date('c'));
    }

    public static function inclusive(string $gatewayId, array $branches, string $joinActivityId = ''): self
    {
        return new self($gatewayId, self::INCLUSIVE, $branches, $joinActivityId, date('c'));
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['gatewayId'] ?? ''),
            (string) ($data['type'] ?? self::EXCLUSIVE),
            (array) ($data['branches'] ?? []),
            (string) ($data['joinActivityId'] ?? ''),
            (string) ($data['createdAt'] ?? '')
        );
    }

    public function gatewayId(): string { return $this->gatewayId; }
    public function type(): string { return $this->type; }
    public function branches(): array { return $this->branches; }
    public function joinActivityId(): string { return $this->joinActivityId; }

    public function toArray(): array
    {
        return [
            'gatewayId' => $this->gatewayId,
            'type' => $this->type,
            'branches' => $this->branches,
            'joinActivityId' => $this->joinActivityId,
            'createdAt' => $this->createdAt !== '' ? $this->createdAt : date('c'),
        ];
    }
}
