<?php


namespace App\Classes\Modules\Transactions\ControllersLogic;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Classes\Modules\Documents\Services\CreatesDocument;
use App\Classes\Modules\Transactions\Services\FetchesTransaction;
use App\Classes\Modules\Transactions\Processors\CreateStorageInvoiceDocTransactionFixProcessor;
use App\Classes\Modules\Transactions\Standards\Rules\CanRegenerateStorageInvoice;
use App\Classes\ValueObjects\Constants\TransactionType;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class RegenerateSingleStorageInvoiceTransactionLogic extends AbstractControllerLogic
{
    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Regenerate Storage Invoice',
            'message' => 'You have successfully regenerated storage invoice'
        ];
    }


    /** @var FetchesTransaction */
    private $fetchesTransaction;

    /** @var CreateStorageInvoiceDocTransactionFixProcessor */
    private $createStorageInvoiceDocTransactionProcessor;

    /** @var CanRegenerateStorageInvoice */
    private $canRegenerateStorageInvoice;

    /**
     * @param CreatesDocument $createsDocument
     */
    public function __construct(FetchesTransaction $fetchesTransaction, CreateStorageInvoiceDocTransactionFixProcessor $createStorageInvoiceDocTransactionProcessor, CanRegenerateStorageInvoice $canRegenerateStorageInvoice)
    {
        $this->fetchesTransaction = $fetchesTransaction;
        $this->createStorageInvoiceDocTransactionProcessor = $createStorageInvoiceDocTransactionProcessor;
        $this->canRegenerateStorageInvoice = $canRegenerateStorageInvoice;
    }

    public function logic(Request $request) : JsonResponse
    {
        $this->canRegenerateStorageInvoice->passes();

        $invoice = $this->fetchesTransaction->execute(['id' => $request->route('invoice_id')]);
        $packingList = $invoice->owner;
        $order = $packingList->owner;
        $invoices = $order->transactions()->where('transactions.type', TransactionType::STORAGE_INVOICE)->get();
        foreach ($invoices as $invoice){
            $invoice->documents()->delete();
        }

        $this->createStorageInvoiceDocTransactionProcessor->execute($packingList, true);
        Log::info(Auth::user()->email." regenerate storage invoice for transaction with id ".$request->route('invoice_id'));

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

}
