package dev.banking.model;

public class BankAccount {

    private final int accountId;
    private long balance;

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

    public int getAccountId() {
        return accountId;
    }

    public synchronized long getBalance() {
        return balance;
    }

    public synchronized void deposit(long amount) {
        balance += amount;
        notifyAll();
    }

    public synchronized void withdraw(long amount) {
        while (balance < amount) {
            try {
                wait();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            }
        }
        balance -= amount;
    }

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

        BankAccount first  = (this.accountId < target.accountId) ? this : target;
        BankAccount second = (this.accountId < target.accountId) ? target : this;

        synchronized (first) {
            synchronized (second) {
                if (this.balance >= amount) {
                    this.balance -= amount;
                    target.balance += amount;
                    target.notifyAll();
                    return;
                }
            }
            this.withdraw(amount);
            target.deposit(amount);
        }
    }
}