package dev.banking.model;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class BankAccount {

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


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

    public int getAccountId() {
        return accountId;
    }


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


    public void deposit(long amount) {
        lock.writeLock().lock();
        try {
            balance += amount;
        }
        finally {
            lock.writeLock().unlock();
        }
    }

    public void withdraw(long amount) {
        lock.writeLock().lock();
        try {
            balance -= amount;
        }
        finally {
            lock.writeLock().unlock();
        }
    }

    /*
     * 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 = this.accountId < target.accountId ? this : target;
        BankAccount second = this.accountId > target.accountId ? this : target;

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