<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Automation;

use DateTime;
use idoit\Module\SyneticsFlows\Automation\Action\ExecutionInfo\ExecutionInfo;
use idoit\Module\SyneticsFlows\Automation\Action\ExecutionResult\ErrorExecutionInterface;
use idoit\Module\SyneticsFlows\Automation\Action\ExecutionResult\ExecutionResult;
use idoit\Module\SyneticsFlows\Automation\Trigger\Invocation\Invocation;
use idoit\Module\SyneticsFlows\Serialization\SerializableTrait;
use idoit\Module\SyneticsFlows\Validation\Required;
use JsonSerializable;

class Execution implements JsonSerializable
{
    use SerializableTrait;

    public function __construct(
        private ?string $id = null,
        #[Required]
        private ?string $flowId = null,
        private ?string $flowTitle = null,
        private ?string $time = null,
        private ?string $started = null,
        private ?string $finished = null,
        private string $status = 'waiting',
        #[Required]
        private ?Invocation $invocation = null,
        private ?ExecutionInfo $execution = null,
        private ?ExecutionResult $result = null,
        private ?string $automationTitle = null,
    )
    {
    }

    public function getId(): ?string
    {
        return $this->id;
    }

    public function setId(?string $id): void
    {
        $this->id = $id;
    }

    public function getTime(): ?string
    {
        return $this->time;
    }

    public function getStatus(): string
    {
        return $this->status;
    }

    public function getFlowId(): ?string
    {
        return $this->flowId;
    }

    public function getInvocation(): ?Invocation
    {
        return $this->invocation;
    }

    public function setExecution(?ExecutionInfo $execution): void
    {
        $this->execution = $execution;
    }

    public function getExecution(): ?ExecutionInfo
    {
        return $this->execution;
    }

    public function getResult(): ?ExecutionResult
    {
        return $this->result;
    }

    public function getStarted(): ?string
    {
        return $this->started;
    }

    public function getFlowTitle(): ?string
    {
        return $this->flowTitle;
    }

    public function getFinished(): ?string
    {
        return $this->finished;
    }

    public function getAutomationTitle(): ?string
    {
        return $this->automationTitle;
    }

    public function start(): void
    {
        $this->started = (new DateTime())->format(DateTime::ATOM);
        $this->status = 'running';
    }

    public function finish(): void
    {
        $this->finished = (new DateTime())->format(DateTime::ATOM);
    }

    public function setResult(?ExecutionResult $result): void
    {
        $this->result = $result;
        $this->status = $result instanceof ErrorExecutionInterface ? 'error' : 'success';
        $this->finish();
    }
}
