<?php

namespace App\Classes\Modules\Bookings\ControllersLogic;


use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Bookings\Services\FetchesBooking;
use App\Classes\Modules\Documents\Services\ApprovesDocument;
use App\Classes\Modules\Documents\Services\FetchesDocument;
use App\Classes\Modules\Documents\Services\RejectsDocument;
use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionProcessor;
use App\Classes\Modules\Transactions\Services\FetchesTransaction;
use App\Classes\Modules\Transactions\Services\UpdatesTransactionStatus;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ApprovePurchaseOrderLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Purchase Order Approval',
            'message' => 'You have successfully updated the Purchase order status'
        ];
    }

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

    /** @var UpdatesTransactionStatus */
    private $updatesTransactionStatus;

    /** @var CreateInvoiceTransactionProcessor */
    private $createInvoiceTransactionProcessor;

    /**
     * ApprovePurchaseOrderLogic constructor.
     * @param FetchesBooking $fetchesBooking
     * @param UpdatesTransactionStatus $updatesTransactionStatus
     * @param CreateInvoiceTransactionProcessor $createInvoiceTransactionProcessor
     */
    public function __construct(FetchesBooking $fetchesBooking, UpdatesTransactionStatus $updatesTransactionStatus, CreateInvoiceTransactionProcessor $createInvoiceTransactionProcessor)
    {
        $this->fetchesBooking = $fetchesBooking;
        $this->updatesTransactionStatus = $updatesTransactionStatus;
        $this->createInvoiceTransactionProcessor = $createInvoiceTransactionProcessor;
    }

    /**
     * @param Request $request
     * @return JsonResponse
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */
    public function logic(Request $request) : JsonResponse
    {

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

        $purchaseOrder = $booking->transactions()->where('type', TransactionType::PURCHASE_ORDER)->first();

        $booking->transactions()->where('type', TransactionType::PURCHASE_ORDER)->where('id', '!=', $purchaseOrder->id)->delete();

        $this->updatesTransactionStatus->execute($purchaseOrder, ApprovalStatus::APPROVED);

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

        return $this->response([]);
    }

}