import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import * as api from "../api";

export const submitProperty = createAsyncThunk(
  'property/submitProperty',
  async (propertyData, { rejectWithValue }) => {
    try {
      const response = await api.submitProperty(propertyData);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);


export const fetchUserProperties = createAsyncThunk(
  'property/fetchUserProperties',
  async (userId, { rejectWithValue }) => {
    try {
      const response = await api.fetchUserProperties(userId);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

export const fetchPropertyById = createAsyncThunk(
  "property/fetchPropertyById",
  async (id, { rejectWithValue }) => {
    try {
      const response = await api.fetchPropertyById(id);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response.data);
    }
  }
);

const propertySlice = createSlice({
  name: 'property',
  initialState: {
    property: {},
    status: 'idle',
    error: null,
    userProperties: [],
    selectedProperty: null,
  },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(submitProperty.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(submitProperty.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.property = action.payload;
      })
      .addCase(submitProperty.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.payload;
      })

      .addCase(fetchUserProperties.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(fetchUserProperties.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.userProperties = action.payload;
      })
      .addCase(fetchUserProperties.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.payload;
      })      

      .addCase(fetchPropertyById.pending, (state) => {
        state.status = "loading";
      })
      .addCase(fetchPropertyById.fulfilled, (state, action) => {
        state.status = "succeeded";
        state.selectedProperty = action.payload;
      })
      .addCase(fetchPropertyById.rejected, (state, action) => {
        state.status = "failed";
        state.error = action.payload;
      });
  },
});

export default propertySlice.reducer;
