<?php

namespace Lucent\Edge;

use Lucent\LucentException;
use Lucent\Validator\Validator as LucentValidator;

final class Edge
{
    /**
     * @throws LucentException
     */
    public function __construct(

        public string $source,
        public string $target,
        public string $sourceSchema,
        public string $targetSchema,
        public string $field,
        public string $rank = "a",
        public int    $depth = 0,
    )
    {


        LucentValidator::single("source", $source, "required|uuid");
        LucentValidator::single("target", $target, "required|uuid");
    }

    public function equal(Edge $edge): bool
    {
        return $this->targetSchema === $edge->targetSchema && $this->field === $edge->field && $this->target === $edge->target && $this->source === $edge->source;
    }

    public function toArray(): array
    {
        return json_decode(json_encode($this), true);
    }

    public function toDB(): array
    {
        $data = $this->toArray();
        unset($data["depth"]);
        return $data;
    }

    public static function fromArray(array $data): Edge
    {

        return new Edge(

            source: data_get($data, 'source'),
            target: data_get($data, 'target'),
            sourceSchema: data_get($data, 'sourceSchema'),
            targetSchema: data_get($data, 'targetSchema'),
            field: data_get($data, 'field'),
            rank: data_get($data, 'rank'),
            depth: data_get($data, 'depth', 0),
        );
    }
}
