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) {
        lock.lock();

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


    public void withdraw(long amount) {
        lock.lock();

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


    public void transfer(BankAccount target, long amount) {
        BankAccount first;
        BankAccount second;

        if (this.accountId < target.accountId) {
            first = this;
            second = target;
        } else {
            first = target;
            second = this;
        }

        first.lock.lock();
        second.lock.lock();

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