<?php

namespace App\Classes\Modules\Wallets\Processors;

use App\Classes\Modules\KeyValuePairs\DataTransferObjects\KeyValuePairObject;
use App\Models\Wallet;
use App\Models\Company;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\Modules\Wallets\Services\CreatesWallet;
use App\Classes\Modules\Wallets\Services\UpdatesWallet;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\Modules\Wallets\Services\GeneratesWalletCode;
use App\Classes\Modules\Transactions\Services\CreatesTransaction;
use App\Classes\Modules\Wallets\DataTransferObjects\WalletObject;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\Modules\KeyValuePairs\Services\CreatesKeyValuePair;
use App\Classes\Modules\KeyValuePairs\Services\UpdatesKeyValuePair;
use App\Classes\ValueObjects\Constants\KVPKey;
use App\Models\Transaction;
use Illuminate\Support\Facades\Log;

class CreditWalletProcessor
{
    /** @var GeneratesWalletCode */
    private $generatesWalletCode;

    /** @var CreatesWallet  */
    private $createsWallet;

    /** @var GeneratesTransactionBillNumber  */
    private $generatesTransactionBillNumber;

    /** @var CreatesTransaction */
    private $createsTransaction;

    /** @var UpdatesWallet */
    private $updatesWallet;

    /** @var CreatesKeyValuePair */
    private $createsKeyValuePair;

    /** @var UpdatesKeyValuePair */
    private $updatesKeyValuePair;


    /**
     * CreateWalletLogic constructor.
     * @param GeneratesWalletCode $generatesWalletCode
     * @param CreatesWallet $createsWallet
     * @param GeneratesTransactionBillNumber $generatesTransactionBillNumber
     * @param CreatesTransaction $createsTransaction
     * @param UpdatesWallet $updatesWallet
     * @param CreatesKeyValuePair $createsKeyValuePair
     * @param UpdatesKeyValuePair $updatesKeyValuePair
     */
    public function __construct(
        GeneratesWalletCode $generatesWalletCode,
        CreatesWallet $createsWallet,
        GeneratesTransactionBillNumber $generatesTransactionBillNumber,
        CreatesTransaction $createsTransaction,
        UpdatesWallet $updatesWallet,
        CreatesKeyValuePair $createsKeyValuePair,
        UpdatesKeyValuePair $updatesKeyValuePair
    )
    {
        $this->generatesWalletCode = $generatesWalletCode;
        $this->createsWallet = $createsWallet;
        $this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
        $this->createsTransaction = $createsTransaction;
        $this->updatesWallet = $updatesWallet;
        $this->createsKeyValuePair = $createsKeyValuePair;
        $this->updatesKeyValuePair = $updatesKeyValuePair;
    }


    /**
     * @param Company $company
     * @param int $transactionType
     * @param float $amount
     * @param string $reference
     * @param $relatedTransaction
     * @return \Illuminate\Database\Eloquent\Model
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */
    public function execute(Company $company, int $transactionType, float $amount, string $reference, $relatedTransaction = null)
    {
        if (!$company->wallets()->first()) {
            $object = new WalletObject($company->id, 1, $this->generatesWalletCode->execute());
            $this->createsWallet->execute($object, $company);
        }

        /** @var Wallet $wallet */
        $wallet = $company->wallets()->first();

        $billNumber = $this->generatesTransactionBillNumber->execute($transactionType === 2 ? 'DEBIT-NOTE-' : 'CREDIT-NOTE-');

        $status = ApprovalStatus::APPROVED;

        $transaction_object = new TransactionObject($billNumber, $transactionType === 2 ? TransactionType::DEBIT_NOTE : TransactionType::CREDIT_NOTE, 1,  $wallet->owner->id,  1, PaymentMethodType::CASH,  $amount,  $amount,  1,  1,  1,  0,  0,  null, $status, [], $reference);
        $transaction = $this->createsTransaction->execute($wallet, $transaction_object);

        if($status === ApprovalStatus::APPROVED){
            $this->updateOrCreateKeyValuePair($transaction, KVPKey::CREDIT_NOTE_APPROVAL_DATE, now());
        }

        $updateWalletAmount = $transactionType === 2 ? ($wallet->amount - $transaction->amount) : ($wallet->amount + $transaction->amount);

        $walletObject = new WalletObject($wallet->owner->id, $wallet->currency_id, $wallet->code, $updateWalletAmount);

        $wallet = $this->updatesWallet->execute($wallet, $walletObject);

        if($relatedTransaction && $relatedTransaction instanceof Transaction){
            $kvp = $relatedTransaction->attributesKVP()->where('key', KVPKey::TRANSACTION_MODEL_CLASS)->where('value', $transaction->id)->latest()->first();
            if(!$kvp){
                $keyValuePairObject = new KeyValuePairObject(
                    KVPKey::TRANSACTION_MODEL_CLASS,
                    $transaction->id
                );
                $this->createsKeyValuePair->execute($relatedTransaction, $keyValuePairObject);
            }
        }
        return $wallet;
    }

    private function updateOrCreateKeyValuePair($transaction, $key, $value)
    {
        $keyValuePairObject = new KeyValuePairObject($key, $value);
        $metadata = $transaction->attributesKVP()->where('key', $key)->first();

        if ($metadata) {
            $this->updatesKeyValuePair->execute($metadata, $keyValuePairObject);
        } else {
            $this->createsKeyValuePair->execute($transaction, $keyValuePairObject);
        }
    }
}
