<?php


namespace App\Classes\Modules\Transactions\ControllersLogic;

use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\Modules\Transactions\Services\FetchesTransaction;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Http\Resources\TransactionResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Classes\Modules\Transactions\Processors\CreatePaymentTransactionProcessor;
use App\Classes\Modules\Transactions\Processors\ReleaseGoodsToCustomerProcessor;
use App\Classes\ValueObjects\Constants\ApprovalStatus;

class CreatePaymentTransactionLogic extends AbstractControllerLogic
{

    /**
     * @return array
     */
    protected function notification():array {
        return [
            'title' => 'Create Payment Transactions',
            'message' => 'You have successfully created currency supplier transactions'
        ];
    }

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

    /** @var CreatePaymentTransactionProcessor */
    private $createPaymentTransactionProcessor;

    /** @var ReleaseGoodsToCustomerProcessor */
    private $releaseGoodsToCustomerProcessor;

    public function __construct(
        FetchesTransaction $fetchesTransaction,
        CreatePaymentTransactionProcessor $createPaymentTransactionProcessor,
        ReleaseGoodsToCustomerProcessor $releaseGoodsToCustomerProcessor
    )
    {
        $this->fetchesTransaction = $fetchesTransaction;
        $this->createPaymentTransactionProcessor = $createPaymentTransactionProcessor;
        $this->releaseGoodsToCustomerProcessor = $releaseGoodsToCustomerProcessor;
    }

    public function logic(Request $request) : JsonResponse
    {
        $payment_method = PaymentMethodType::PAYMENT_METHODS[$request->input('payment_method')];

        $invoice_transaction = $this->fetchesTransaction->execute(['id' => $request->input('transaction_id')]);

        if($invoice_transaction->status === ApprovalStatus::APPROVED){
            $payment_transaction = $this->createPaymentTransactionProcessor->execute($invoice_transaction, $payment_method , $request->input('bank_code'), false);

            if($payment_transaction && $payment_transaction->status === ApprovalStatus::APPROVED){
                $pL = $invoice_transaction->owner;
                $this->releaseGoodsToCustomerProcessor->execute($pL, $invoice_transaction);
            }
            return $this->resourceResponse(new TransactionResource($payment_transaction));
        }

        $response =  ['message' => 'A transaction might be suspended; please check if there is any dispute in progress.'];
        return $this->response(['data' => $response]);
    }



}
