package dev.banking.model;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;

public class BankAccount {

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

    /*
     * Students may introduce additional fields
     * such as:
     * - Lock / ReentrantLock
     * - ReadWriteLock
     * - Object monitor
     * - etc.
     */

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

    public int getAccountId() {
        return accountId;
    }

    /*
     * TODO:
     * Return the current balance in a thread-safe way.
     *
     * Requirements:
     * - Must be safe under concurrent reads/writes
     * - Should not block unnecessarily if using read/write locks
     */
    public synchronized long getBalance() { //??????????????????????????/?
        return balance;
    }

    /*
     * TODO:
     * Increase balance atomically.
     *
     * Requirements:
     * - Must not lose updates under concurrency
     */
    public synchronized void deposit(long amount) {
        balance += amount;
    }

    /*
     * TODO:
     * Decrease balance atomically.
     *
     * Requirements:
     * - Must not cause race conditions
     * - Negative balance handling is NOT required unless you decide
     *   to extend the system (optional)
     */
    public synchronized void withdraw(long amount) {
        balance -= amount;
    }

    /*
     * TODO:
     * Transfer money between two accounts atomically.
     *
     * IMPORTANT REQUIREMENTS:
     * - Must be atomic (no partial transfer)
     * - Must be deadlock-free
     * - Must protect both source and target accounts
     *
     * HINT:
     * - Consider global lock ordering using accountId
     * - Or tryLock with retry strategy
     */
    public void transfer(BankAccount target, long amount) {
        BankAccount first = target.getAccountId() < accountId ? target : this ;
        BankAccount second = target.getAccountId() < accountId ? this : target ;

        synchronized (first) {
            synchronized (second) {
                target.deposit(amount);
                this.withdraw(amount);
            }
        }
    }
}