<?php

namespace App\Classes\Modules\PackingLists\ControllersLogic\Containers;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\PackingLists\Services\Containers\FetchesContainer;
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\ContainerResource;
use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Carbon\Carbon;

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

    /** @var FetchesContainer */
    private $fetchesContainer;

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

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

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


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

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

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

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

            return $this->resourceResponse(new ContainerResource($container));

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

    }

}
