<?php

namespace App\Classes\Modules\PackingLists\ControllersLogic;


use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\PackingLists\Services\DeletesPackingList;
use App\Classes\Modules\PackingLists\Services\FetchesPackingList;
use App\Classes\Modules\PackingLists\Services\Packages\FetchesPackage;
use App\Classes\Modules\PackingLists\Standards\Rules\CanDeletePackingList;
use App\Classes\ValueObjects\Constants\PackingListType;
use App\Models\PackingList;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DeletePackingListByPackageIdLogic extends AbstractControllerLogic
{
    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Deleted PackingList',
            'message' => 'You have successfully deleted a PackingList'
        ];
    }


    /** @var CanDeletePackingList */
    private $canDeletePackingList;

    /** @var DeletesPackingList */
    private $deletesPackingList;

    /** @var FetchesPackingList */
    private $fetchesPackingList;

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

    /**
     * DeletePackingListByPackageIdLogic constructor.
     * @param CanDeletePackingList $canDeletePackingList
     * @param DeletesPackingList $deletesPackingList
     * @param FetchesPackingList $fetchesPackingList
     * @param FetchesPackage $fetchesPackage
     */
    public function __construct(CanDeletePackingList $canDeletePackingList, DeletesPackingList $deletesPackingList, FetchesPackingList $fetchesPackingList, FetchesPackage $fetchesPackage)
    {
        $this->canDeletePackingList = $canDeletePackingList;
        $this->deletesPackingList = $deletesPackingList;
        $this->fetchesPackingList = $fetchesPackingList;
        $this->fetchesPackage = $fetchesPackage;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ErrorException
     */
    public function logic(Request $request) : JsonResponse
    {
        $this->canDeletePackingList->passes();

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

        $packingList = $package->packingList;

        $packingList = PackingList::where('reference', $packingList->reference)->get();

        $childPackingList = PackingList::where('owner_type', PackingList::class)->whereIn('owner_id', $packingList->pluck('id'))->get();

        $packingList->each->delete();

        $childPackingList->each->delete();

        return $this->response([]);
    }

}
