<?php

namespace OtomaticAi\Services;

use OtomaticAi\Models\Contracts\Publishable;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

class PublicationGenerationState
{
    private Publishable $publishable;

    public function __construct(Publishable $publishable)
    {
        $this->publishable = $publishable;
    }

    public function getState(): array
    {
        return $this->publishable->generation_state ?? [];
    }

    public function setStatus(string $status)
    {
        $state = $this->getState();
        Arr::set($state, "status", $status);
        $this->setState($state);
    }

    public function setState(array $state)
    {
        $this->publishable->generation_state = $state;
        $this->save();
    }

    public function save()
    {
        $this->publishable->saveQuietly();
    }

    // steps methods
    public function getSteps(): array
    {
        return Arr::get($this->getState(), "steps", []);
    }

    public function getStep(string $step): ?array
    {
        return Arr::get($this->getSteps(), $step);
    }

    public function getCurrentStep(): ?array
    {
        $state = $this->getState();
        $currentStep = Arr::get($state, "current_step");

        if (!$currentStep) {
            return null;
        }

        return $this->getStep($currentStep);
    }

    public function setCurrentStep(string $step)
    {
        $state = $this->getState();
        Arr::set($state, "current_step", $step);
        $this->setState($state);
    }

    public function getNextStep(): ?array
    {
        $state = $this->getState();
        $steps = Arr::get($state, "steps", []);
        return Arr::first($steps, function ($step) {
            return $step["status"] === "idle";
        });
    }

    public function setStepStatus(string $step, string $status)
    {
        $state = $this->getState();
        Arr::set($state, "steps." . $step . ".status", $status);
        $this->setState($state);
    }

    // artifacts methods
    public function getArtifacts(): array
    {
        return Arr::get($this->getState(), "artifacts", []);
    }

    public function getArtifact(string $artifact, $default = null)
    {
        return Arr::get($this->getState(), "artifacts." . $artifact, $default);
    }

    public function setArtifact(string $artifact, $value)
    {
        $state = $this->getState();
        Arr::set($state, "artifacts." . $artifact, $value);
        $this->setState($state);
    }
}
