// /redux/slices/database/poiTypesSlice.js
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

// API-Abruf für POI-Typen
export const fetchPoiTypes = createAsyncThunk("poiTypes/fetchPoiTypes", async () => {
  let API_BASE_URL = "";

  if (typeof window !== "undefined") {
    // Browser
    API_BASE_URL = `${window.location.protocol}//${window.location.hostname}:3000`;
  } else {
    // Server (z. B. SSR)
    API_BASE_URL = "http://localhost:3000"; // oder env-Fallback z. B. process.env.API_BASE_URL
  }

  const response = await fetch(`${API_BASE_URL}/api/talas_v5_DB/poiTyp/readPoiTyp`);
  return await response.json();
});

const poiTypesSlice = createSlice({
  name: "poiTypes",
  initialState: { data: [], status: "idle" },
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(fetchPoiTypes.pending, (state) => {
        state.status = "loading";
      })
      .addCase(fetchPoiTypes.fulfilled, (state, action) => {
        state.data = action.payload;
        state.status = "succeeded";
      })
      .addCase(fetchPoiTypes.rejected, (state) => {
        state.status = "failed";
      });
  },
});

export default poiTypesSlice.reducer;
