<?php

namespace App\Classes\Modules\Addresses\ControllersLogic;


use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Addresses\Services\UpdatesAddress;
use App\Classes\Modules\Addresses\Services\FetchesAddress;
use App\Classes\Modules\Addresses\Standards\Rules\CanUpdateAddress;
use App\Classes\Modules\Addresses\DataTransferObjects\AddressObject;
use App\Http\Resources\AddressResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UpdateAddressLogic extends AbstractControllerLogic
{

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

    /** @var CanUpdateAddress */
    private $canUpdateAddress;

    /** @var UpdatesAddress */
    private $updatesAddress;

    /** @var FetchesAddress */
    private $fetchesAddress;

    /**
     * UpdateAddressLogic constructor.
     * @param CanUpdateAddress $canUpdateAddress
     * @param UpdatesAddress $updatesAddress
     * @param FetchesAddress $fetchesAddress
     */
    public function __construct(CanUpdateAddress $canUpdateAddress, UpdatesAddress $updatesAddress, FetchesAddress $fetchesAddress)
    {
        $this->canUpdateAddress = $canUpdateAddress;
        $this->updatesAddress = $updatesAddress;
        $this->fetchesAddress = $fetchesAddress;
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ErrorException
     */
    public function logic(Request $request) : JsonResponse
    {
        try {

            $object = new AddressObject($request->input('company_id'), $request->input('street_one'), $request->input('street_two'), $request->input('city'), $request->input('state'), $request->input('post_code'), $request->input('country'), $request->input('default'), $request->input('billing'));

            $this->canUpdateAddress->passes($object);

            $query = $this->fetchesAddress->execute(['id' => $request->route('id')]);

            $query = $this->updatesAddress->execute($query, $object);

            return $this->resourceResponse(new AddressResource($query));


        } catch (\Exception $exception){
            throw new ErrorException($exception->getMessage(), $exception->getCode());
        }

    }

}