<?php

namespace App\Classes\Modules\KeyValuePairs\Services;


use App\Classes\General\Eloquent\AbstractUpdateRelationshipRecord;
use App\Classes\General\Interfaces\KeyValueInterface;
use App\Classes\Modules\KeyValuePairs\DataTransferObjects\KeyValuePairObject;
use App\Models\KeyValuePair;

class CreatesKeyValuePair extends AbstractUpdateRelationshipRecord
{
    /**
     * @param KeyValueInterface $kv
     * @param KeyValuePairObject $object
     * @return \Illuminate\Database\Eloquent\Model
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */

    public function execute(?KeyValueInterface $kv, KeyValuePairObject $object) {
        $model = new KeyValuePair();
        $model->key = $object->getKey();
        $model->value = $object->getValue();

        // Owner-less
        if (is_null($kv)) {
            $model->owner_type = null;
            $model->owner_id = null;
            $model->save();
            return $model;
        }

        return $this->handler($kv->attributesKVP(), $model);
    }
}
