package dev.banking.model;

import java.util.concurrent.locks.ReentrantLock;

public class BankAccount {

    private final int accountId;
    private long balance;

    // explicit ReentrantLock associated with each individual account
    // to provide independent lock contention per account
    private final ReentrantLock lock = new ReentrantLock();

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

    public int getAccountId() {
        return accountId;
    }

    /*
     * Return the current balance in a thread-safe way.
     */
    public long getBalance() {
        lock.lock();
        try {
            return this.balance;
        } finally {
            lock.unlock();
        }
    }

    /*
     * increase balance atomically
     */
    public void deposit(long amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Deposit amount must be positive.");
        }
        lock.lock();
        try {
            this.balance += amount;
        } finally {
            lock.unlock();
        }
    }

    /*
     * Decrease balance atomically
     */
    public void withdraw(long amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Withdrawal amount must be positive.");
        }
        lock.lock();
        try {
            this.balance -= amount;
        } finally {
            lock.unlock();
        }
    }


    public void transfer(BankAccount target, long amount) {
        if (target == null) {
            throw new IllegalArgumentException("Target account cannot be null.");
        }
        if (this.accountId == target.getAccountId()) {
            throw new IllegalArgumentException("Cannot transfer to the same account.");
        }
        if (amount <= 0) {
            throw new IllegalArgumentException("Transfer amount must be positive.");
        }

        // Establish an absolute ordering to acquire locks
        BankAccount firstLock = this.accountId < target.getAccountId() ? this : target;
        BankAccount secondLock = this.accountId < target.getAccountId() ? target : this;

        firstLock.lock.lock();
        try {
            secondLock.lock.lock();
            try {
                // Perform the atomic transfer operations
                this.withdraw(amount);
                target.deposit(amount);
            } finally {
                secondLock.lock.unlock();
            }
        } finally {
            firstLock.lock.unlock();
        }
    }
}