<?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 Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Classes\Exceptions\MalformedRequestException;
use App\Classes\ValueObjects\Constants\BookingAttributeNames;

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

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

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

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws MalformedRequestException
     */
    public function logic(Request $request) : JsonResponse
    {
        if (!$request['order_reference_no']) {
            throw new MalformedRequestException('At least 1 order reference required.');
        }

        if ($request['order_reference_no']) {
            foreach ($request['order_reference_no'] as $index => $reference) {
                if (!$reference) {
                    $index += 1;
                    throw new MalformedRequestException("Order reference {$index} cannot be empty");
                }
            }
        }

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

        foreach ($request['order_reference_no'] as $order_reference) {
            $booking->modelAttributes()->create([
                'name' => BookingAttributeNames::ORDER_REFERENCE_NO,
                'value' => $order_reference
            ]);
        }

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

}