<?php

namespace App\Classes\Modules\Addresses\ControllersLogic;


use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Addresses\Services\CreatesAddress;
use App\Classes\Modules\Addresses\Services\ResetsAddressDefault;
use App\Classes\Modules\Addresses\Services\SetsAddressDefault;
use App\Classes\Modules\Addresses\Standards\Rules\CanCreateAddress;
use App\Classes\Modules\Addresses\DataTransferObjects\AddressObject;
use App\Http\Resources\AddressResource;
use App\Models\Address;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CreateAddressLogic extends AbstractControllerLogic
{
    /**
     * CreateAddressLogic constructor.
     * @param CanCreateAddress $canCreateAddress
     * @param CreatesAddress $createsAddress
     * @param ResetsAddressDefault $resetsAddressDefault
     * @param SetsAddressDefault $setsAddressDefault
     */
    public function __construct(CanCreateAddress $canCreateAddress, CreatesAddress $createsAddress, ResetsAddressDefault $resetsAddressDefault, SetsAddressDefault $setsAddressDefault)
    {
        $this->canCreateAddress = $canCreateAddress;
        $this->createsAddress = $createsAddress;
        $this->resetsAddressDefault = $resetsAddressDefault;
        $this->setsAddressDefault = $setsAddressDefault;
    }


    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Created Address',
            'message' => 'You have successfully created a new Address'
        ];
    }

    /** @var CanCreateAddress */
    private $canCreateAddress;

    /** @var CreatesAddress */
    private $createsAddress;

    /** @var ResetsAddressDefault */
    private $resetsAddressDefault;

    /** @var SetsAddressDefault */
    private $setsAddressDefault;



    /**
     * @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->canCreateAddress->passes($object);

            /** @var Address $query */
            $query = $this->createsAddress->execute($object);

            $this->resetsAddressDefault->execute($query);

            $this->setsAddressDefault->execute($query);

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

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

    }

}