<?php

namespace NioModules\CryptoWallet\Services;

use App\Rules\TnxRef;
use App\Models\Transaction;
use App\Models\UserTempMeta;
use Illuminate\Http\Request;
use App\Enums\TransactionStatus;
use Illuminate\Validation\ValidationException;

class TransactionConfirmationService
{
    public function saveReference($request, $transaction)
    {
        $validatedReference = data_get($request, 'reference');
        $trimmedReference = trim_input($validatedReference);
        $transaction->reference = $trimmedReference;
        $transaction->status = TransactionStatus::ONHOLD;
        $transaction->save();

        UserTempMeta::where('user_id', auth()->id())
                    ->where('meta_key', 'deposit_details')
                    ->delete();
    }

    public function findTransaction($tnxHash)
    {
        $tnx = get_hash($tnxHash);
        $transaction = Transaction::loggedUser()
            ->where('tnx', $tnx)
            ->where('status', TransactionStatus::PENDING)
            ->whereNull('reference')
            ->first();

        if (blank($transaction)) {
            throw ValidationException::withMessages(['tnx' => __('Invalid Transaction!')]);
        }

        return $transaction;
    }
}
