import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { Deal, DealUpdate } from '@/types/deals';
import { RootState } from '@/store/store';

interface DealState {
  deals: Deal[];
  loading: boolean;
  error: string | null;
}

const initialState: DealState = {
  deals: [],
  loading: false,
  error: null
};

export const fetchDeals = createAsyncThunk('deals/fetchDeals', async () => {
  const response = await fetch('/api/deals');
  if (!response.ok) throw new Error('Failed to fetch deals');
  return response.json();
});

export const updateDeal = createAsyncThunk('deals/updateDeal', async (dealUpdate: DealUpdate) => {
  const response = await fetch(`/api/deals/${dealUpdate.id}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(dealUpdate)
  });
  if (!response.ok) throw new Error('Failed to update deal');
  return response.json();
});

const dealSlice = createSlice({
  name: 'deals',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchDeals.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchDeals.fulfilled, (state, action) => {
        state.deals = action.payload;
        state.loading = false;
      })
      .addCase(fetchDeals.rejected, (state, action) => {
        state.loading = false;
        state.error = action.error.message || 'Failed to fetch deals';
      })
      .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 const selectDeals = (state: RootState) => state.deals.deals;
export default dealSlice.reducer;