<?php

namespace App\Classes\Modules\PackingLists\ControllersLogic;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\PackingLists\Services\FetchesPackingList;
use App\Classes\Modules\Schedules\Services\CreatesSchedule;
use App\Classes\Modules\Schedules\Services\UpdatesScheduleStatus;
use App\Classes\Modules\Schedules\DataTransferObjects\ScheduleObject;
use App\Classes\ValueObjects\Constants\ApprovalStatus;

use App\Http\Resources\PackingListResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Carbon\Carbon;

class ReschedulePackingListLogic extends AbstractControllerLogic
{
    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Reschedule Packing List',
            'message' => 'You have successfully Reschedule Packing List'
        ];
    }

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

    /** @var UpdatesScheduleStatus */
    private $updatesScheduleStatus;

    /** @var CreatesSchedule */
    private $createsSchedule;

    /**
     * DeleteContainerControllersLogic constructor.
     * @param FetchesPackingList $fetchesPackingList
     * @param CreatesSchedule $createsSchedule
     */
    public function __construct(FetchesPackingList $fetchesPackingList, UpdatesScheduleStatus $updatesScheduleStatus, CreatesSchedule $createsSchedule)
    {
        $this->fetchesPackingList = $fetchesPackingList;
        $this->updatesScheduleStatus = $updatesScheduleStatus;
        $this->createsSchedule = $createsSchedule;
    }


    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ErrorException
     */
    public function logic(Request $request) : JsonResponse
    {
        try {
            $packing_list = $this->fetchesPackingList->execute(['id' => $request->route('id')]);

            $transport = $packing_list->transports()->first();

            $old_sechedule = $transport->schedules()->first();

            $this->updatesScheduleStatus->execute($old_sechedule, ApprovalStatus::REJECTED);

            $scheduleObject = new ScheduleObject(
                Carbon::parse($request->input('eta')), 
                Carbon::parse($request->input('etd')), 
                ApprovalStatus::APPROVED
             );
            $schedule = $this->createsSchedule->execute($transport, $scheduleObject);

            return $this->resourceResponse(new PackingListResource($packing_list));

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

    }

}
