<?php


namespace App\Classes\Modules\Transactions\ControllersLogic;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Transactions\Services\FetchesTransaction;
use App\Classes\Modules\Transactions\Services\UpdatesTransactionStatus;
use App\Classes\Modules\Transactions\Services\FetchesGroup;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Models\Transaction;
use App\Models\Wallet;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class DeletePaymentTransactionLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Delete Payment Transaction',
            'message' => 'You have successfully deleted the payment transaction'
        ];
    }

    /** @var FetchesGroup */
    private $fetchesGroup;

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

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


    /**
     * SuspendTransactionLogic constructor.
     * @param FetchesTransaction $fetchesTransaction
     * @param UpdatesTransactionStatus $updatesTransactionStatus
     * @param FetchesGroup $fetchesGroup
     */
    public function __construct(FetchesTransaction $fetchesTransaction, UpdatesTransactionStatus $updatesTransactionStatus, FetchesGroup $fetchesGroup)
    {
        $this->fetchesTransaction = $fetchesTransaction;
        $this->updatesTransactionStatus = $updatesTransactionStatus;
        $this->fetchesGroup = $fetchesGroup;
    }


    public function logic(Request $request) : JsonResponse
    {
        $transaction = $this->fetchesTransaction->execute(['id' => $request->route('id')]);

        if($transaction->owner instanceof Wallet){
            try{
                $group = $this->fetchesGroup->execute(['reference' => $transaction->payment_reference]);
                $group->status = ApprovalStatus::SUSPENDED;
                $group->save();
            }
            catch(\Exception $excaption){
                Log::info('No group associated with transaction with payment_reference - '.$transaction->payment_reference);
            }
        }

        $transaction->delete();

        $invoice = $transaction->owner;
        if ($invoice instanceof Transaction) {
            $this->updatesTransactionStatus->execute($invoice, ApprovalStatus::APPROVED);
        }

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