import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit'
import axios from 'axios'
import {rejectNotify, resetNotify} from "../../helpers/notifyStateHandler";

interface MainState {
    transactions: any[]
    loading: boolean
    count: number
    refetch: boolean;
    notify: {
        showNotification: boolean
        textNotification: string
        typeNotification: string
    }
}

const initialState: MainState = {
    transactions: [],
    loading: false,
    count: 0,
    refetch: false,
    notify: {
        showNotification: false,
        textNotification: '',
        typeNotification: 'warn',
    },
}

export const fetchTransactions = createAsyncThunk('transactions/fetch', async (data: any) => {
    const { query } = data
    const result = await axios.get(
        `transactions${query || ''}`
    )
    return {rows: result.data.rows, count: result.data.count};
})

export const transactionsSlice = createSlice({
    name: 'transactions',
    initialState,
    reducers: {
        setRefetch: (state, action: PayloadAction<boolean>) => {
            state.refetch = action.payload;
        },
    },
    extraReducers: (builder) => {
        builder.addCase(fetchTransactions.pending, (state) => {
            state.loading = true
            resetNotify(state);
        })
        builder.addCase(fetchTransactions.rejected, (state, action) => {
            state.loading = false
            rejectNotify(state, action);
        })

        builder.addCase(fetchTransactions.fulfilled, (state, action) => {
            state.transactions = action.payload.rows;
            state.count = action.payload.count;
            state.loading = false
        })
    },
})

export const { setRefetch } = transactionsSlice.actions

export default transactionsSlice.reducer
