import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { cashOutWallet, paymentListing, cashWalletHistory } from "../api/api";

interface TransactionState {
  cashOutWallet: any;
  paymentList: any;
  cashWalletHistoryData: any;
  walletDetails: any;
  loading: boolean;
  error: string | null;
}

const initialState: TransactionState = {
  cashOutWallet: [],
  paymentList: [],
  cashWalletHistoryData: [],
  walletDetails: null,
  loading: false,
  error: null,
};

const transactionSlice = createSlice({
  name: "transaction",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      // Cash Out Wallet
      .addCase(cashOutWallet.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(cashOutWallet.fulfilled, (state, action: PayloadAction<any>) => {
        state.loading = false;
        state.cashOutWallet = action.payload;
      })
      .addCase(cashOutWallet.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || "Failed to fetch cash out wallet";
      })

      // Payment Listing
      .addCase(paymentListing.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(paymentListing.fulfilled, (state, action: PayloadAction<any>) => {
        state.loading = false;
        state.paymentList = action.payload;
      })
      .addCase(paymentListing.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || "Failed to fetch payment listing";
      })

      // Cash Wallet History
      .addCase(cashWalletHistory.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(cashWalletHistory.fulfilled, (state, action: PayloadAction<any>) => {
        state.loading = false;
        // If action.payload is already an array, just assign it to state
        state.cashWalletHistoryData = action.payload.data || action.payload;
      })
      .addCase(cashWalletHistory.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || "Failed to fetch all wallet transactions";
      });
  },
});

export default transactionSlice.reducer;
