import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import API from "../api";

const baseURL = process.env.NEXT_PUBLIC_BASE_URL;

export const getShippingAddress = createAsyncThunk(
  "get/shippingAddress",
  async (payload: any, thunkAPI) => {
    try {
      const response: any = await API.get(
        `${baseURL}/order/existing_shipping_address/${payload.id}`
      );
      if (response.data === undefined || typeof response.data !== "object") {
        return thunkAPI.rejectWithValue("Invalid data received");
      }

      return response?.data;
    } catch (error: any) {
      const message =
        (error.response &&
          error.response.data &&
          error.response.data?.message) ||
        error.message ||
        error.toString();
      return thunkAPI.rejectWithValue(message);
    }
  }
);

interface getShippingAddressState {
  isGetShippingAddressSuccess: boolean;
  shippingAddressData: any | null;
  isGetShippingAddressError: string | undefined;
  isGetShippingAddressLoading: boolean;
}

const initialState: getShippingAddressState = {
  isGetShippingAddressSuccess: false,
  shippingAddressData: null,
  isGetShippingAddressError: "",
  isGetShippingAddressLoading: false,
};

const getShippingAddressSlice = createSlice({
  name: "getShippingAddress",
  initialState,
  reducers: {
    resetShippingAddress: (state: getShippingAddressState) => {
      state.isGetShippingAddressSuccess = false;
      state.shippingAddressData = null;
      state.isGetShippingAddressError = "";
      state.isGetShippingAddressLoading = false;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(getShippingAddress.pending, (state: getShippingAddressState) => {
        state.isGetShippingAddressLoading = true;
        state.isGetShippingAddressError = "";
        state.shippingAddressData = null;
        state.isGetShippingAddressSuccess = false;
      })
      .addCase(
        getShippingAddress.fulfilled,
        (
          state: getShippingAddressState,
          action: ReturnType<typeof getShippingAddress.fulfilled>
        ) => {
          state.isGetShippingAddressLoading = false;
          state.shippingAddressData = action?.payload?.data;
          state.isGetShippingAddressSuccess = true;
          state.isGetShippingAddressError = "";
        }
      )
      .addCase(
        getShippingAddress.rejected,
        (state: getShippingAddressState, action: any) => {
          state.isGetShippingAddressLoading = false;
          state.isGetShippingAddressError =
            action?.payload || "An error occurred";
          state.isGetShippingAddressSuccess = false;
          state.shippingAddressData = null; // Reset user in case of rejection
        }
      );
  },
});

export const { resetShippingAddress } = getShippingAddressSlice.actions;

export default getShippingAddressSlice.reducer;
