import { createSlice } from '@reduxjs/toolkit';
import { addReview, reviewsHistory } from '../api/api'; // Adjust the import as necessary


interface ReviewState {
  reviewData: any | null;
  reviewHistoryData : any;
  successMessage: string | null;
  loading: boolean;
  error: string | null;
}

const initialState: ReviewState = {
  reviewData: null,
  reviewHistoryData:[],
  successMessage: null,
  loading: false,
  error: null,
};

const reviewSlice = createSlice({
  name: 'review',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(addReview.pending, (state) => {
        state.loading = true;
        state.error = null;
        state.successMessage = null;
      })
      .addCase(addReview.fulfilled, (state, action) => {
        state.loading = false;
        state.reviewData = action.payload.review;
        state.successMessage = action.payload.message;
      })
      .addCase(addReview.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || 'Failed to add review';
      })
      // Reviews History
      .addCase(reviewsHistory.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(reviewsHistory.fulfilled, (state, action) => {
        state.loading = false;
        state.reviewHistoryData = action.payload;
      })
      .addCase(reviewsHistory.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export default reviewSlice.reducer;
