import {BalanceInfo, BalanceTransaction} from "../../types/balance";
import {createAsyncThunk, createSlice} from "@reduxjs/toolkit";
import balanceApi from "../../api/balanceApi";

const name = 'balance';

interface TransactionsState {
    items: BalanceTransaction[];
    isLoading: boolean;
    currentPage: number;
    hasNext: boolean;
}

interface BalanceState {
    balance: number;
    transactions: TransactionsState;
}

const transactionsInitialState: TransactionsState = {
    currentPage: 1,
    hasNext: true,
    isLoading: false,
    items: []
}
const initialState: BalanceState = {
    balance: 0,
    transactions: transactionsInitialState
}


export const fetchTransactions = createAsyncThunk(
    `${name}/fetchTransactions`,
    async (page: number, _): Promise<BalanceTransaction[]> => {
        const response = await balanceApi.getTransactions(page);
        return response.balanceTransactions;
    }
)

export const fetchBalance = createAsyncThunk(
    `${name}/fetchBalance`,
    async (_): Promise<BalanceInfo> => {
        return await balanceApi.getBalanceInfo();
    }
)
export const balanceSlice = createSlice({
    name: name,
    initialState,
    reducers: {
        refreshTransactions: (state) => {
            state.transactions = transactionsInitialState;
        }
    },
    extraReducers: (builder) => {
        builder.addCase(fetchTransactions.pending, (state, action) => {
            state.transactions.isLoading = true;
        })
        builder.addCase(fetchTransactions.fulfilled, (state, action) => {
            state.transactions.isLoading = false;
            state.transactions.hasNext = action.payload.length > 0;
            state.transactions.items = [...state.transactions.items, ...action.payload];
            state.transactions.currentPage = state.transactions.currentPage + 1;
        })
        builder.addCase(fetchBalance.fulfilled, (state, action) => {
            state.balance = action.payload.balance;
        })
    }
})

export const {refreshTransactions} = balanceSlice.actions;

export default balanceSlice.reducer;