import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { api } from '@/services/api';

export const fetchPipelineData = createAsyncThunk(
  'pipeline/fetchData',
  async (_, { rejectWithValue }) => {
    try {
      const response = await api.get('/pipeline/deals');
      return response.data;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

export const updateDeal = createAsyncThunk(
  'pipeline/updateDeal',
  async (deal, { rejectWithValue }) => {
    try {
      const response = await api.put(`/pipeline/deals/${deal.id}`, deal);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.message);
    }
  }
);

const pipelineSlice = createSlice({
  name: 'pipeline',
  initialState: {
    deals: [],
    loading: false,
    error: null
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchPipelineData.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchPipelineData.fulfilled, (state, action) => {
        state.loading = false;
        state.deals = action.payload;
      })
      .addCase(fetchPipelineData.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      .addCase(updateDeal.fulfilled, (state, action) => {
        const index = state.deals.findIndex((deal) => deal.id === action.payload.id);
        if (index !== -1) {
          state.deals[index] = action.payload;
        }
      });
  }
});

export default pipelineSlice.reducer;