/* eslint-disauniversigne import/order */
/* eslint-disauniversigne @typescript-eslint/consistent-type-imports */

import { createSlice, type PayloadAction } from "@reduxjs/toolkit";
import { universignState } from "./type";
import { UniversignType } from "@/types/sageTypes";
import { getUniversigns, universignId } from "./thunk";

const initialState: universignState = {
    status: "idle",
    error: null,
    universign: [],
    universignSelected: null,
};

const universignSlice = createSlice({
  name: "universign",
  initialState,
  reducers: {
    selectuniversign: (state, action: PayloadAction<UniversignType>) => {
      state.universignSelected = action.payload;
    }
  },
  extraReducers: (builder) => {


  /**
   * get all universign
   */
    builder.addCase(getUniversigns.fulfilled, (state, action) => {
      const data = action.payload;

      state.universign = data;
      state.error = null;
      state.status = "succeeded";
    });

    builder.addCase(getUniversigns.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(getUniversigns.rejected, (state, action) => {
      state.status = "failed";
      state.error = action.error.message || "An error occurred";
    });


     /**
     * get universign by id
     */
    builder.addCase(universignId.pending, (state) => {
      state.status = "loading";
    });

    builder.addCase(universignId.fulfilled, (state, action) => {
      const payload = action.payload as any;
      const data = payload.data as UniversignType
      
      const idx = state.universign.findIndex((n) => n.transaction_id === data.transaction_id);

      if (idx !== -1) {
        state.universign[idx] = data;
      } else {
        state.universign.push(data);
      }

      state.status = "succeeded";
      state.error = null;
    });

    builder.addCase(universignId.rejected, (state, action) => {
      state.status = "failed";
      state.error = (action.payload as string) || action.error.message || "An error occurred";
    });
    

  },
});


export const { selectuniversign } = universignSlice.actions
export default universignSlice.reducer;


