<?php

namespace App\Classes\Modules\KeyValuePairs\ControllersLogic;


use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\KeyValuePairs\DataTransferObjects\KeyValuePairObject;
use App\Classes\Modules\ServiceTypes\Standards\Rules\CanUpdateServiceType;
use App\Classes\Modules\KeyValuePairs\Services\CreatesKeyValuePair;
use App\Classes\Modules\KeyValuePairs\Services\UpdatesKeyValuePair;
use App\Http\Resources\LockResource;
use App\Models\KeyValuePair;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UpdateLockLogic extends AbstractControllerLogic
{


    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Updated Lock Status',
            'message' => 'You have successfully updated the Lock status'
        ];
    }

    // /** @var CanUpdateServiceType */
    // private $canUpdateServiceType;

    /** @var CreatesKeyValuePair */
    private $createsKeyValuePair;

    /** @var UpdatesKeyValuePair */
    private $updatesKeyValuePair;

    /**
     * UpdateLockLogic constructor.
     * @param CanUpdateServiceType $canUpdateServiceType
     * @param CreatesKeyValuePair $createsKeyValuePair
     * @param UpdatesKeyValuePair $updatesKeyValuePair
     */
    public function __construct(CanUpdateServiceType $canUpdateServiceType, CreatesKeyValuePair $createsKeyValuePair, UpdatesKeyValuePair $updatesKeyValuePair)
    {
        // $this->canUpdateServiceType = $canUpdateServiceType;
        $this->createsKeyValuePair = $createsKeyValuePair;
        $this->updatesKeyValuePair = $updatesKeyValuePair;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Classes\Exceptions\AccessForbiddenException
     * @throws \App\Classes\Exceptions\MalformedRequestException
     * @throws \App\Classes\Exceptions\RequestValidationException
     */
    public function logic(Request $request) : JsonResponse
    {
        // cief todo: 110 - CanUpdateLock

        $key = $request->input('key');
        $kvp = KeyValuePair::whereNull('owner_type')
            ->whereNull('owner_id')
            ->where('key', $key)
            ->first();
        $value = ($kvp->value === "1") ? "0" : "1";
        $this->updateOrCreateKeyValuePair($key, $value);
        return $this->resourceResponse(new LockResource($kvp));

    }

    private function updateOrCreateKeyValuePair($key, $value)
    {
        $keyValuePairObject = new KeyValuePairObject($key, $value);
        $kvp = KeyValuePair::whereNull('owner_type')
            ->whereNull('owner_id')
            ->where('key', $key)
            ->first();

        if ($kvp) {
            $this->updatesKeyValuePair->execute($kvp, $keyValuePairObject);
        } else {
            $this->createsKeyValuePair->execute(null, $keyValuePairObject);
        }
    }

}
