<?php

namespace App\Classes\Modules\PackingList\Packages\Items\ControllersLogic;

use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\PackingLists\Services\Packages\Items\CreatesItem;
use App\Classes\Modules\Orders\Services\FetchesOrder;
use App\Classes\Modules\PackingLists\Standards\Rules\Packages\Items\CanCreatePackageItem;
use App\Classes\Modules\PackingLists\DataTransferObjects\ItemObject;
use App\Classes\Modules\Companies\Services\FetchesCompany;
use App\Classes\Modules\Packages\Services\FetchesPackage;
use App\Http\Resources\ItemResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CreatePackageItemLogic extends AbstractControllerLogic
{

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

    /** @var CanCreatePackageItem */
    private $canCreatePackageItem;

    /** @var FetchesPackage */
    private $fetchesPackage;

    /** @var CreatesItem */
    private $createsPackageItem;

    /**
     * CreatePackageItemLogic constructor.
     * @param CanCreatePackageItem $canCreatePackageItem
     * @param FetchesPackage $fetchesPackage
     * @param CreatesItem $createsPackageItem
     */
    public function __construct(CanCreatePackageItem $canCreatePackageItem, FetchesPackage $fetchesPackage, CreatesItem $createsPackageItem)
    {
        $this->canCreatePackageItem = $canCreatePackageItem;
        $this->fetchesPackage = $fetchesPackage;
        $this->createsPackageItem = $createsPackageItem;
    }

    /**
     * @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
    {

        $package = $this->fetchesPackage->execute(['id' => $request->input('package_id')]);

        $reference_no = rand(1000000, 9999999);

        $object = new ItemObject(
            $package->id,
            $request->input('name'),
            $reference_no,
            $request->input('description'),
            $request->input('quantity'),
            $request->input('uom'),
            $request->input('price'),
            $request->input('total'),
            ApprovalStatus::PENDING_SUBMISSION);

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

        $query = $this->createsPackageItem->execute($object);

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

    }

}
