package com.bindstone.graphbank.service;

import com.bindstone.graphbank.domain.Account;
import com.bindstone.graphbank.domain.Currency;
import com.bindstone.graphbank.domain.Transaction;
import com.bindstone.graphbank.provider.CurrencyProvider;
import org.apache.commons.lang3.exception.ContextedException;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class TransactionServiceTest extends AbstractServiceTest {
    @Autowired
    private TransactionService service;
    @Autowired
    private AccountService accountService;
    @Autowired
    private CurrencyService currencyService;

    @Test
    public void transferTest() throws ContextedException {
        Currency currency = currencyService.findByIso("EUR");
        if (Objects.isNull(currency)) {
            currency = currencyService.save(CurrencyProvider.EURO());
        }

        Account account1 = accountService.save(
                Account.getBuilder("ACCOUNT_1")
                        .currency(currency)
                        .value(100)
                        .build());
        Account account2 = accountService.save(
                Account.getBuilder("ACCOUNT_2")
                        .currency(currency)
                        .value(100)
                        .build());
        service.transfer(account1, account2, 1, 10);

        /** FROM **/
        List<Transaction> transactions1 = service.findByAccount(account1);
        assertEquals("Size is not 1", 1, transactions1.size());
        Transaction t1 = transactions1.get(0);
        assertEquals("First transaction", 1, t1.getTransactionNumber());
        assertTrue("Value", (10 + t1.getValue() == 0));

        Account validate1 = accountService.findById(account1.getId());
        assertEquals("Transaction Number", 1, validate1.getTransactionCounter());
        System.out.println("Value:" + validate1.getValue());
        assertTrue("Value", (90 - validate1.getValue() == 0));

        /** TO **/
        List<Transaction> transactions2 = service.findByAccount(account2);
        assertEquals("Size is not 1", 1, transactions2.size());
        Transaction t2 = transactions2.get(0);
        assertEquals("First transaction", 1, t2.getTransactionNumber());
        assertTrue("Value", (10 - t2.getValue() == 0));

        Account validate2 = accountService.findById(account2.getId());
        assertEquals("Transaction Number", 1, validate2.getTransactionCounter());
        System.out.println("Value:" + validate2.getValue());
        assertTrue("Value", (110 - validate2.getValue() == 0));
    }

}
