import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import { aa as getErrorMessage$1 } from "./common-B0qL-cCR.esm.js";
const validateApiClient = (apiClient, requiredMethods) => {
  for (const method of requiredMethods) {
    if (typeof apiClient[method] !== "function") {
      console.warn(`API client missing required method: ${method}`);
      return false;
    }
  }
  return true;
};
const API_METHOD_GROUPS = {
  share: ["getV1PagesUserList", "postV1PagesShare"],
  header: ["getV1Languages"],
  reportsTitleBar: ["getV1Company"],
  inventoryReportsTitleBar: ["getV1InventoryItems", "getV1WarehouseLocation", "getV1AssemblyItems", "getV1BillsOfMaterials"]
};
const createConfiguredApiClient = (baseApiClient, getAuthToken) => {
  const configuredClient = {};
  Object.keys(baseApiClient).forEach((methodName) => {
    if (typeof baseApiClient[methodName] === "function") {
      configuredClient[methodName] = async (params = {}) => {
        const authToken = getAuthToken();
        return baseApiClient[methodName]({ ...authToken, ...params });
      };
    }
  });
  return configuredClient;
};
const setLoadingState = (state, key, isLoading = true) => {
  if (state[key] && typeof state[key] === "object") {
    state[key] = { ...state[key], isLoading, isError: false, error: "" };
  }
};
const setErrorState = (state, key, error) => {
  if (state[key] && typeof state[key] === "object") {
    state[key] = { ...state[key], isLoading: false, isError: true, error };
  }
};
const createModuleSlice = ({
  name,
  initialState: initialState2,
  actions,
  reducers,
  extraReducers
}) => {
  return createSlice({
    name,
    initialState: initialState2,
    reducers: {
      setPaginationModel: (state, { payload }) => {
        if ("paginationModel" in state && typeof state.paginationModel === "object") {
          state.paginationModel = { ...state.paginationModel, ...payload };
        }
      },
      setOptionsData: (state, { payload }) => {
        if ("optionsData" in state && typeof state.optionsData === "object") {
          state.optionsData = { ...state.optionsData, ...payload };
        }
      },
      setStaticOptions: (state, { payload }) => {
        state.staticOptions = { ...state.staticOptions, ...payload };
      },
      resetState: () => initialState2,
      ...reducers
    },
    extraReducers: (builder) => {
      Object.entries(actions).forEach(([stateKey, actionGroup]) => {
        if (actionGroup) {
          Object.entries(actionGroup).forEach(([actionName, action]) => {
            if (action && "pending" in action && "fulfilled" in action && "rejected" in action) {
              builder.addCase(action.pending, (state) => setLoadingState(state, stateKey)).addCase(action.fulfilled, (state, { payload }) => {
                if (state[stateKey] && typeof state[stateKey] === "object") {
                  state[stateKey] = {
                    ...state[stateKey],
                    isLoading: false,
                    ...(payload == null ? void 0 : payload.rows) ? { rows: payload.rows } : {},
                    ...(payload == null ? void 0 : payload.data) ? { data: payload.data } : {},
                    ...(payload == null ? void 0 : payload.fields) ? { fields: payload.fields } : {},
                    ...(payload == null ? void 0 : payload.activityLogs) ? { activityLogs: payload.activityLogs } : {},
                    ...(payload == null ? void 0 : payload.pagination) ? { pagination: payload.pagination } : {}
                  };
                  if (payload == null ? void 0 : payload.pagination) {
                    state.paginationModel = { ...state.paginationModel, ...payload.pagination };
                  }
                }
              }).addCase(
                action.rejected,
                (state, { error }) => {
                  setErrorState(state, stateKey, getErrorMessage$1(error == null ? void 0 : error.message));
                }
              );
            }
          });
        }
      });
      if (extraReducers) {
        extraReducers(builder);
      }
    }
  });
};
const initialState$3 = {
  languagesData: {
    isLoading: false,
    isError: false,
    error: "",
    data: []
  },
  currentLanguage: {
    label: "English",
    code: "en",
    direction: "ltr"
  }
};
const getErrorMessage = (message) => {
  return message || "An error occurred";
};
const fetchLanguages = createAsyncThunk(
  "header/language/get",
  async (_, { extra }) => {
    var _a, _b, _c;
    if (!((_a = extra == null ? void 0 : extra.apiClient) == null ? void 0 : _a.getV1Languages)) {
      throw new Error("API client not configured for header slice");
    }
    const response = await extra.apiClient.getV1Languages({
      order: `id:1`
    });
    const data = ((_b = response == null ? void 0 : response.data) == null ? void 0 : _b.languages) || [];
    const languages = (_c = data == null ? void 0 : data.filter((d) => d == null ? void 0 : d.is_active)) == null ? void 0 : _c.map((d) => {
      return {
        label: d == null ? void 0 : d.name,
        code: d == null ? void 0 : d.code,
        direction: d == null ? void 0 : d.direction
      };
    });
    return { languages };
  }
);
const headerSlice = createSlice({
  name: "header",
  initialState: initialState$3,
  reducers: {
    setLanguages(state, { payload }) {
      state.languagesData = { ...state.languagesData, ...payload };
    },
    setCurrentLanguage(state, { payload }) {
      state.currentLanguage = { ...state.currentLanguage, ...payload };
    },
    setLanguagesData(state, { payload }) {
      state.languagesData = payload;
    },
    resetLanguagesState(state) {
      state.languagesData = initialState$3.languagesData;
    },
    resetHeaderState(state) {
      Object.assign(state, initialState$3);
    }
  },
  extraReducers: (builder) => {
    builder.addCase(fetchLanguages.pending, (state) => {
      state.languagesData = {
        isLoading: true,
        isError: false,
        error: "",
        data: []
      };
    }).addCase(fetchLanguages.fulfilled, (state, { payload }) => {
      state.languagesData = {
        isLoading: false,
        isError: false,
        error: "",
        data: payload.languages || []
      };
    }).addCase(fetchLanguages.rejected, (state, { error }) => {
      const m = getErrorMessage(error.message);
      state.languagesData = {
        isLoading: false,
        isError: true,
        error: m,
        data: []
      };
    });
  }
});
const {
  setLanguages,
  setCurrentLanguage,
  setLanguagesData,
  resetLanguagesState,
  resetHeaderState
} = headerSlice.actions;
const headerSlice_default = headerSlice.reducer;
const initialState$2 = {
  companies: [],
  items: [],
  warehouseLocations: [],
  isLoading: true,
  assemblyItems: [],
  bomData: [],
  error: "",
  isError: false
};
const fetchOptions = createAsyncThunk(
  "inventoryReportsTitleBar/fetchOptions",
  async (_, { extra }) => {
    if (!(extra == null ? void 0 : extra.apiClient)) {
      throw new Error("API client not configured for inventory reports title bar slice");
    }
    const { apiClient } = extra;
    const [i, c, wl, ai] = await Promise.all([
      handleFetchItem(apiClient),
      handleFetchCompanies(apiClient),
      handleFetchWarehouseLocations(apiClient),
      fetchAssemblyItems(apiClient)
    ]);
    return { i, c, wl, ai };
  }
);
const fetchBom = createAsyncThunk(
  "inventoryReportsTitleBar/fetchBom",
  async (_, { extra }) => {
    var _a;
    if (!((_a = extra == null ? void 0 : extra.apiClient) == null ? void 0 : _a.getV1BillsOfMaterials)) {
      throw new Error("API client not configured for BOM fetch");
    }
    const bom = await fetchBomData(extra.apiClient);
    return { bom };
  }
);
const handleFetchCompanies = async (apiClient) => {
  var _a;
  try {
    if (!apiClient.getV1Company) {
      throw new Error("getV1Company not available in API client");
    }
    const response = await apiClient.getV1Company();
    return ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.company) || [];
  } catch (error) {
    console.error("Error fetching companies:", error);
    return [];
  }
};
const handleFetchItem = async (apiClient) => {
  var _a;
  try {
    if (!apiClient.getV1InventoryItems) {
      throw new Error("getV1InventoryItems not available in API client");
    }
    const response = await apiClient.getV1InventoryItems({
      skip: 0,
      limit: 999,
      filters: `(type.eq=inventory|type.eq=assembly&is_variant.eq=false|self_variant.eq=true)`
    });
    return ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.inventoryItemsList) || [];
  } catch (error) {
    console.error("Error fetching items:", error);
    return [];
  }
};
const handleFetchWarehouseLocations = async (apiClient) => {
  var _a;
  try {
    if (!apiClient.getV1WarehouseLocation) {
      throw new Error("getV1WarehouseLocation not available in API client");
    }
    const response = await apiClient.getV1WarehouseLocation({
      skip: 0,
      limit: 999
    });
    return ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.warehouseLocationList) || [];
  } catch (error) {
    console.error("Error fetching warehouse locations:", error);
    return [];
  }
};
const fetchAssemblyItems = async (apiClient) => {
  var _a;
  try {
    if (!apiClient.getV1AssemblyItems) {
      throw new Error("getV1AssemblyItems not available in API client");
    }
    const response = await apiClient.getV1AssemblyItems({
      skip: 0,
      limit: 999
    });
    return ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.assemblyItemsList) || [];
  } catch (error) {
    console.error("Error fetching assembly items:", error);
    return [];
  }
};
const fetchBomData = async (apiClient) => {
  var _a;
  try {
    const response = await apiClient.getV1BillsOfMaterials({
      skip: 0,
      limit: 99999
    });
    return ((_a = response == null ? void 0 : response.data) == null ? void 0 : _a.bom_list) || [];
  } catch (error) {
    console.error("Error fetching BOM data:", error);
    return [];
  }
};
const inventoryReportsTitleBarSlice = createSlice({
  name: "inventoryReportsTitleBar",
  initialState: initialState$2,
  reducers: {
    setCompanies: (state, action) => {
      state.companies = action.payload;
    },
    setItems: (state, action) => {
      state.items = action.payload;
    },
    setWarehouseLocations: (state, action) => {
      state.warehouseLocations = action.payload;
    },
    setAssemblyItems: (state, action) => {
      state.assemblyItems = action.payload;
    },
    setBomData: (state, action) => {
      state.bomData = action.payload;
    },
    setLoading: (state, action) => {
      state.isLoading = action.payload;
    },
    setError: (state, action) => {
      state.error = action.payload;
      state.isError = !!action.payload;
    },
    resetInventoryReportsTitleBarState: (state) => {
      Object.assign(state, initialState$2);
    }
  },
  extraReducers: (builder) => {
    builder.addCase(fetchOptions.pending, (state) => {
      state.companies = [];
      state.items = [];
      state.warehouseLocations = [];
      state.assemblyItems = [];
      state.isLoading = true;
      state.error = "";
      state.isError = false;
    });
    builder.addCase(fetchOptions.fulfilled, (state, action) => {
      var _a, _b, _c, _d;
      state.companies = ((_a = action.payload) == null ? void 0 : _a.c) || [];
      state.items = ((_b = action.payload) == null ? void 0 : _b.i) || [];
      state.warehouseLocations = ((_c = action.payload) == null ? void 0 : _c.wl) || [];
      state.assemblyItems = ((_d = action.payload) == null ? void 0 : _d.ai) || [];
      state.isLoading = false;
      state.isError = false;
      state.error = "";
    });
    builder.addCase(fetchOptions.rejected, (state, action) => {
      state.isLoading = false;
      state.error = action.error.message || "Failed to fetch options";
      state.isError = true;
    });
    builder.addCase(fetchBom.fulfilled, (state, action) => {
      var _a;
      state.bomData = ((_a = action.payload) == null ? void 0 : _a.bom) || [];
    });
    builder.addCase(fetchBom.rejected, (state, action) => {
      state.error = action.error.message || "Failed to fetch BOM data";
      state.isError = true;
    });
  }
});
const {
  setCompanies: setCompanies$1,
  setItems,
  setWarehouseLocations,
  setAssemblyItems,
  setBomData,
  setLoading: setLoading$2,
  setError: setError$2,
  resetInventoryReportsTitleBarState
} = inventoryReportsTitleBarSlice.actions;
const inventoryReportsTitleBarSlice_default = inventoryReportsTitleBarSlice.reducer;
const initialState$1 = {
  companies: [],
  isLoading: true,
  error: "",
  isError: false
};
const fetchCompanies = createAsyncThunk(
  "reportsTitleBar/fetchCompanies",
  async (_, { extra }) => {
    var _a;
    if (!((_a = extra == null ? void 0 : extra.apiClient) == null ? void 0 : _a.getV1Company)) {
      throw new Error("API client not configured for reports title bar slice");
    }
    const response = await extra.apiClient.getV1Company();
    return response;
  }
);
const reportsTitleBarSlice = createSlice({
  name: "reportsTitleBar",
  initialState: initialState$1,
  reducers: {
    setCompanies: (state, action) => {
      state.companies = action.payload;
    },
    setLoading: (state, action) => {
      state.isLoading = action.payload;
    },
    setError: (state, action) => {
      state.error = action.payload;
      state.isError = !!action.payload;
    },
    resetReportsTitleBarState: (state) => {
      Object.assign(state, initialState$1);
    }
  },
  extraReducers: (builder) => {
    builder.addCase(fetchCompanies.pending, (state) => {
      state.isLoading = true;
      state.error = "";
      state.companies = [];
      state.isError = false;
    });
    builder.addCase(fetchCompanies.fulfilled, (state, action) => {
      var _a, _b;
      state.companies = ((_b = (_a = action.payload) == null ? void 0 : _a.data) == null ? void 0 : _b.company) || [];
      state.isLoading = false;
      state.isError = false;
      state.error = "";
    });
    builder.addCase(fetchCompanies.rejected, (state, action) => {
      state.isLoading = false;
      state.error = action.error.message || "Failed to fetch companies";
      state.isError = true;
    });
  }
});
const {
  setCompanies,
  setLoading: setLoading$1,
  setError: setError$1,
  resetReportsTitleBarState
} = reportsTitleBarSlice.actions;
const reportsTitleBarSlice_default = reportsTitleBarSlice.reducer;
const initialState = {
  users: [],
  departments: [],
  loading: true,
  error: "",
  isError: false
};
const getAllUserAndDepartmentDropdown = createAsyncThunk(
  "share/getUser",
  async (_, { extra }) => {
    var _a;
    if (!((_a = extra == null ? void 0 : extra.apiClient) == null ? void 0 : _a.getV1PagesUserList)) {
      throw new Error("API client not configured for share slice");
    }
    const response = await extra.apiClient.getV1PagesUserList();
    return response;
  }
);
const sharePage = createAsyncThunk(
  "share/sharePage",
  async (data, { extra }) => {
    var _a;
    if (!((_a = extra == null ? void 0 : extra.apiClient) == null ? void 0 : _a.postV1PagesShare)) {
      throw new Error("API client not configured for share slice");
    }
    const response = await extra.apiClient.postV1PagesShare(data);
    return response;
  }
);
const shareSlice = createSlice({
  name: "share",
  initialState,
  reducers: {
    // Synchronous actions for direct state updates
    setUsers: (state, action) => {
      state.users = action.payload;
    },
    setDepartments: (state, action) => {
      state.departments = action.payload;
    },
    setLoading: (state, action) => {
      state.loading = action.payload;
    },
    setError: (state, action) => {
      state.error = action.payload;
      state.isError = !!action.payload;
    },
    resetState: (state) => {
      Object.assign(state, initialState);
    }
  },
  extraReducers: (builder) => {
    builder.addCase(getAllUserAndDepartmentDropdown.pending, (state) => {
      state.loading = true;
      state.error = "";
      state.users = [];
      state.departments = [];
      state.isError = false;
    });
    builder.addCase(
      getAllUserAndDepartmentDropdown.fulfilled,
      (state, action) => {
        var _a, _b, _c, _d, _e, _f;
        state.loading = false;
        state.users = ((_c = (_b = (_a = action.payload) == null ? void 0 : _a.data) == null ? void 0 : _b.users) == null ? void 0 : _c.map((user) => ({
          ...user,
          label: `${user.first_name} ${user.last_name}`,
          value: user.id
        }))) || [];
        state.departments = ((_f = (_e = (_d = action.payload) == null ? void 0 : _d.data) == null ? void 0 : _e.roles) == null ? void 0 : _f.map((role) => ({
          ...role,
          label: role.name,
          value: role.id
        }))) || [];
        state.error = "";
        state.isError = false;
      }
    );
    builder.addCase(
      getAllUserAndDepartmentDropdown.rejected,
      (state, action) => {
        state.loading = false;
        state.error = action.error.message || "Failed to fetch users and departments";
        state.isError = true;
      }
    );
    builder.addCase(sharePage.pending, (state) => {
      state.loading = true;
      state.error = "";
      state.isError = false;
    });
    builder.addCase(sharePage.fulfilled, (state) => {
      state.loading = false;
      state.error = "";
      state.isError = false;
    });
    builder.addCase(sharePage.rejected, (state, action) => {
      state.loading = false;
      state.error = action.error.message || "Failed to share page";
      state.isError = true;
    });
  }
});
const { setUsers, setDepartments, setLoading, setError, resetState } = shareSlice.actions;
const shareSlice_default = shareSlice.reducer;
export {
  API_METHOD_GROUPS as A,
  validateApiClient as B,
  createModuleSlice as a,
  fetchCompanies as b,
  createConfiguredApiClient as c,
  fetchLanguages as d,
  fetchOptions as e,
  fetchBom as f,
  getAllUserAndDepartmentDropdown as g,
  headerSlice_default as h,
  inventoryReportsTitleBarSlice_default as i,
  resetHeaderState as j,
  resetInventoryReportsTitleBarState as k,
  resetLanguagesState as l,
  resetReportsTitleBarState as m,
  resetState as n,
  setBomData as o,
  setCurrentLanguage as p,
  setDepartments as q,
  reportsTitleBarSlice_default as r,
  setAssemblyItems as s,
  setItems as t,
  setLanguages as u,
  setLanguagesData as v,
  setUsers as w,
  setWarehouseLocations as x,
  sharePage as y,
  shareSlice_default as z
};
//# sourceMappingURL=shareSlice-Di1XniXV.esm.js.map
