<?php

namespace App\Classes\Modules\Bookings\ControllersLogic;

use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\Modules\Bookings\Services\CancelsBooking;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Http\Resources\BookingResource;

use App\Classes\General\Abstracts\AbstractControllerLogic;

use App\Classes\Modules\Bookings\Services\FetchesBooking;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CancelBookingLogic extends AbstractControllerLogic
{

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


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

    /** @var CancelsBooking */
    private $cancelsBooking;

    /**
     * CancelBookingLogic constructor.
     * @param FetchesBooking $fetchesBooking
     * @param CancelsBooking $cancelsBooking
     */
    public function __construct(FetchesBooking $fetchesBooking, CancelsBooking $cancelsBooking)
    {
        $this->fetchesBooking = $fetchesBooking;
        $this->cancelsBooking = $cancelsBooking;
    }

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

        $bookingActivePayments = $booking->transactions()->where('type', '=', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])->get();

        if(count($bookingActivePayments)){
            throw new MalformedRequestException('You can\'t cancel an order with active payments');
        }

        $this->cancelsBooking->execute($booking);

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

}