package dev.banking.model;
import java.util.concurrent.locks.ReentrantLock;
public class BankAccount {

    private final int accountId;
    private long balance;
    private final ReentrantLock lock = new ReentrantLock();

    public BankAccount(int accountId, long initialBalance) {
        this.accountId = accountId;
        this.balance = initialBalance;
    }

    public int getAccountId() {
        return accountId;
    }

    public long getBalance() {
        lock.lock();
        try {
            return balance;
        } finally {
            lock.unlock();
        }
    }

    public void deposit(long amount) {
        if (amount <= 0) return;

        lock.lock();
        try {
            balance += amount;
        } finally {
            lock.unlock();
        }
    }

    public void withdraw(long amount) {
        if (amount <= 0) return;

        lock.lock();
        try {
            balance -= amount;
        } finally {
            lock.unlock();
        }
    }

    public void transfer(BankAccount target, long amount) {
        if (this == target || amount <= 0) {
            return;
        }

        BankAccount firstLock = this.accountId < target.getAccountId() ? this : target;
        BankAccount secondLock = this.accountId < target.getAccountId() ? target : this;

        firstLock.lock.lock();
        try {
            secondLock.lock.lock();
            try {
                this.balance -= amount;
                target.balance += amount;
            } finally {
                secondLock.lock.unlock();
            }
        } finally {
            firstLock.lock.unlock();
        }
    }
}