import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import * as api from "../api";


export const showUser = createAsyncThunk('user/showUser', async (userId, { rejectWithValue }) => {
  try {
      const response = await api.showUser(userId);
      // console.log("response", response);
      return response.data;
  } catch (error) {
      return rejectWithValue(error.response.data);
  }
});

export const verifyEmail = createAsyncThunk(
  "user/verifyEmail",
  async ({id, token, data}, { rejectWithValue }) => {
    try {
      const response = await api.verifyEmail(id, token, data);
      return response.data.message;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

const userSlice = createSlice({
  name: "user",
  initialState: {
    users: [], 
    error: "",
    loading: false,
    verified: false,
    // user: null,

    user: {},

  },
  reducers: {},
  extraReducers: (builder) => {
    builder
    .addCase(showUser.pending, (state) => {
      state.loading = true;
      state.error = null;
  })
  .addCase(showUser.fulfilled, (state, action) => {
      state.loading = false;
      state.user = action.payload;
  })
  .addCase(showUser.rejected, (state, action) => {
      state.loading = false;
      state.error = action.payload;
  })
      .addCase(verifyEmail.pending, (state) => {
        state.loading = true;
        state.error = null;
      })

      .addCase(verifyEmail.fulfilled, (state, action) => {
        state.loading = false;
        state.verified = action.payload === "Email verified successfully";
        // state.verified = true;
      })

      .addCase(verifyEmail.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message;
      });


  },
});

export default userSlice.reducer;
