<?php

namespace App\Classes\Modules\Bookings\ControllersLogic;

use App\Http\Resources\BookingResource;

use App\Classes\General\Abstracts\AbstractControllerLogic;

use App\Classes\Modules\Bookings\Services\FetchesBooking;

use App\Classes\Modules\Bookings\Standards\Rules\CanUpdateBooking;
use App\Classes\Modules\Bookings\Services\UpdatesBooking;
use App\Classes\Modules\Bookings\DataTransferObjects\BookingObject;

use ErrorException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UpdateBookingLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Updated Booking',
            'message' => 'You have successfully updated the Booking'
        ];
    }

    /** @var CanUpdateBooking */
    private $canUpdateBooking;

    /** @var UpdatesBooking */
    private $updatesBooking;

    /** @var FetchesBooking */
    private $fetchesBooking;


    /**
     * UpdateBookingLogic constructor.
     * @param CanUpdateBooking $canUpdateBooking
     * @param UpdatesBooking $updatesBooking
     * @param FetchesBooking $fetchesBooking
     */
    public function __construct(
        CanUpdateBooking $canUpdateBooking, 
        UpdatesBooking $updatesBooking, 
        FetchesBooking $fetchesBooking
    )
    {
        $this->canUpdateBooking = $canUpdateBooking;
        $this->updatesBooking = $updatesBooking;
        $this->fetchesBooking = $fetchesBooking;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws ErrorException
     */
    public function logic(Request $request) : JsonResponse
    {
        try {
            DB::beginTransaction();

            $booking = $this->fetchesBooking->execute(['id' => $request->route('id')]);

            $booking_object = new BookingObject(
                $booking->company_id,
                $request->input('transferable_bank_id', $booking->transferable_bank_id),
                $booking->marking,
                $request->input('reference', $booking->reference),
                $request->input('fix_amount', $booking->fix_amount),
                $request->input('fix_currency_id', $booking->fix_currency_id),
                $request->input('convertible_currency_id', $booking->convertible_currency_id),
                $request->input('conversion_currency_id', $booking->conversion_currency_id)
            );
            $this->canUpdateBooking->passes($booking_object);
            $booking = $this->updatesBooking->execute($booking, $booking_object);
            
            DB::commit();

            return $this->resourceResponse(new BookingResource($booking));

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

}