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

interface Service {
  id: string;
  name: string;
  desc: string;
  groupId: string;
}

interface ServicesState {
  services: Service[];
  loading: boolean;
  error: string | null;
}

const initialState: ServicesState = {
  services: [],
  loading: false,
  error: null,
};

export const fetchServices = createAsyncThunk(
  'services/fetchServices',
  async (_, { rejectWithValue }) => {
    try {
      console.log('Fetching services from Redux thunk...');
      const response = await axios.get('http://127.0.0.1:8000/api/services/', {
        headers: {
          'Accept': 'application/json',
        },
      });
      console.log('Services fetched successfully:', response.data);
      return response.data;
    } catch (error) {
      console.error('Error in fetchServices thunk:', error);
      if (axios.isAxiosError(error)) {
        const errorMessage = error.response?.data?.error || error.response?.data?.details || error.message;
        return rejectWithValue(errorMessage);
      }
      return rejectWithValue('An unexpected error occurred while fetching services');
    }
  }
);

const servicesSlice = createSlice({
  name: 'services',
  initialState,
  reducers: {
    clearServicesError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchServices.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchServices.fulfilled, (state, action) => {
        state.loading = false;
        state.services = action.payload;
        state.error = null;
      })
      .addCase(fetchServices.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string || 'Failed to fetch services';
      });
  },
});

export const { clearServicesError } = servicesSlice.actions;
export default servicesSlice.reducer; 