<?php

namespace App\Repositories;

use App\Models\PaymentTransaction;

class PaymentTransactionRepository
{
    public function lockById(int $id): ?PaymentTransaction
    {
        return PaymentTransaction::query()->whereKey($id)->lockForUpdate()->first();
    }

    public function findByGatewayReference(string $gateway, string $gatewayTxnId, string $merchantRef): ?PaymentTransaction
    {
        if ($gatewayTxnId !== '') {
            $byGatewayTxn = PaymentTransaction::query()
                ->where('gateway', $gateway)
                ->where('gateway_transaction_id', $gatewayTxnId)
                ->latest('id')
                ->first();
            if ($byGatewayTxn) {
                return $byGatewayTxn;
            }
        }

        if ($merchantRef === '') {
            return null;
        }

        return PaymentTransaction::query()
            ->where('gateway', $gateway)
            ->where('merchant_order_ref', $merchantRef)
            ->latest('id')
            ->first();
    }
}
