
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import axios from 'axios';

interface Entity {
  id: string;
  name: string;
  type: 'merchant' | 'firm';
  registration?: string;
}

interface ContextState {
  availableMerchants: Entity[];
  availableFirms: Entity[];
  activeContext: Entity | null;
  isLoading: boolean;
  error: string | null;
}

const initialState: ContextState = {
  availableMerchants: [],
  availableFirms: [],
  activeContext: null,
  isLoading: false,
  error: null,
};

export const fetchAvailableContexts = createAsyncThunk(
  'context/fetchAvailableContexts',
  async (_, { rejectWithValue }) => {
    try {
      const response = await axios.get('/context/available');
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

export const contextSlice = createSlice({
  name: 'context',
  initialState,
  reducers: {
    setActiveContext: (state, action: PayloadAction<Entity>) => {
      state.activeContext = action.payload;
      localStorage.setItem('activeContext', JSON.stringify(action.payload));
    },
    loadActiveContext: (state) => {
      const saved = localStorage.getItem('activeContext');
      if (saved) {
        state.activeContext = JSON.parse(saved);
      }
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchAvailableContexts.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(fetchAvailableContexts.fulfilled, (state, action) => {
        state.isLoading = false;
        state.availableMerchants = action.payload.merchants;
        state.availableFirms = action.payload.firms;
        
        // If no active context, set the first merchant as default if available
        if (!state.activeContext) {
            const saved = localStorage.getItem('activeContext');
            if (saved) {
                state.activeContext = JSON.parse(saved);
            } else if (action.payload.merchants.length > 0) {
                state.activeContext = action.payload.merchants[0];
            } else if (action.payload.firms.length > 0) {
                state.activeContext = action.payload.firms[0];
            }
        }
      })
      .addCase(fetchAvailableContexts.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload as string;
      });
  },
});

export const { setActiveContext, loadActiveContext } = contextSlice.actions;

export default contextSlice.reducer;
