"use strict";
const _ = require("lodash");
const React = require("react");
const pageContext = require("./page-context-PMwS3EGo.js");
const apiConfig = require("./api-config-DXwDMFn-.js");
const common = require("./common-B47boGYI.js");
const api = require("./api-BygscvSz.js");
const notistack = require("notistack");
function useDeepMemo(value) {
  const ref = React.useRef();
  if (!_.isEqual(ref.current, value)) {
    ref.current = value;
  }
  return ref.current;
}
const usePermissions = () => {
  const context = React.useContext(pageContext.PermissionsContext);
  if (!context) {
    throw new Error("usePermissions must be used within a PermissionsProvider");
  }
  return context;
};
const usePages = (defaultColumns = []) => {
  const context = React.useContext(pageContext.PageContext);
  if (!context) {
    throw new Error("usePages must be used within a PageProvider");
  }
  if (context.initializeColumns) {
    context.initializeColumns(defaultColumns);
  }
  return context;
};
const useLocationFilter = ({
  selectedCompany,
  setValue,
  fieldArrayName,
  locationFieldName,
  resetValue = null,
  filterKey = "&company_id.in",
  isDirty = false
}) => {
  React.useEffect(() => {
    if (setValue && fieldArrayName && locationFieldName && isDirty) {
      setValue(`${fieldArrayName}.${locationFieldName}`, resetValue);
    }
  }, [isDirty, setValue, fieldArrayName, locationFieldName, resetValue]);
  const locationFilter = React.useMemo(() => {
    const companyId = Array.isArray(selectedCompany) ? (selectedCompany == null ? void 0 : selectedCompany.length) ? selectedCompany : null : selectedCompany || null;
    console.log("🚀 ~ useLocationFilter ~ companyId:", companyId);
    if (companyId === null) {
      return {};
    }
    return {
      [filterKey]: companyId
    };
  }, [selectedCompany, filterKey]);
  return locationFilter;
};
const useMultipleLocationFilters = ({
  selectedCompany,
  setValue,
  fieldConfigs,
  resetValue = void 0,
  filterKey = "&company_id.in"
}) => {
  return React.useMemo(() => {
    const companyId = (selectedCompany == null ? void 0 : selectedCompany.length) > 0 ? selectedCompany : 0;
    console.log("🚀 ~ useLocationFilter ~ companyId:", companyId);
    fieldConfigs.forEach(({ fieldArrayName, locationFieldName }) => {
      if (setValue && fieldArrayName && locationFieldName) {
        setValue(`${fieldArrayName}.${locationFieldName}`, resetValue);
      }
    });
    return {
      [filterKey]: companyId
    };
  }, [selectedCompany, setValue, fieldConfigs, resetValue, filterKey]);
};
function apiHelper({
  res,
  callBack,
  showError = true,
  errorCallback,
  successMessage = null,
  enqueueSnackbar
}) {
  var _a;
  if (((_a = res == null ? void 0 : res.meta) == null ? void 0 : _a.requestStatus) === "rejected") {
    const errorMessage = (() => {
      var _a2, _b, _c, _d;
      try {
        const msg = ((_a2 = res.error) == null ? void 0 : _a2.message) || ((_b = res == null ? void 0 : res.payload) == null ? void 0 : _b.message);
        return msg ? JSON.parse(msg) : null;
      } catch {
        return { message: ((_c = res.error) == null ? void 0 : _c.message) || ((_d = res == null ? void 0 : res.payload) == null ? void 0 : _d.message) || "Something went wrong" };
      }
    })();
    const rawError = errorMessage == null ? void 0 : errorMessage.message;
    let message = "Something went wrong";
    if (typeof rawError === "string") {
      message = rawError.replace("Error:", "").trim();
    } else if (rawError && typeof rawError === "object") {
      message = rawError.message || JSON.stringify(rawError);
    } else if (rawError) {
      message = String(rawError);
    }
    console.log("🚀 ~ apiHelper ~ rawError:", rawError);
    console.log("🚀 ~ apiHelper ~ showError:", showError);
    if (showError && typeof enqueueSnackbar === "function") {
      enqueueSnackbar(message, { variant: "error" });
    }
    if (errorCallback && typeof errorCallback === "function") {
      errorCallback(message);
    }
    return;
  }
  if (successMessage && typeof enqueueSnackbar === "function") {
    enqueueSnackbar(successMessage);
  }
  if (callBack && typeof callBack === "function") {
    callBack();
  }
}
function useApi() {
  const { enqueueSnackbar } = notistack.useSnackbar();
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const callApi = React.useCallback(async ({
    apiFunc,
    onSuccess,
    onError,
    successMessage,
    errorMessage,
    loadingState,
    enableLoading = true,
    showError = true
  }) => {
    if (enableLoading) setLoading(true);
    loadingState == null ? void 0 : loadingState(true);
    let response;
    try {
      response = await apiFunc();
    } catch (err) {
      response = {
        meta: { requestStatus: "rejected" },
        error: { message: (err == null ? void 0 : err.message) || "Something went wrong" }
      };
    }
    if (enableLoading) setLoading(false);
    loadingState == null ? void 0 : loadingState(false);
    apiHelper(
      {
        res: response,
        callBack: () => {
          onSuccess == null ? void 0 : onSuccess(response);
        },
        errorCallback: (err) => {
          onError == null ? void 0 : onError(response);
          setError(errorMessage || err);
        },
        successMessage,
        showError,
        enqueueSnackbar
      }
    );
    return { response, error };
  }, [enqueueSnackbar]);
  return { callApi, loading, error };
}
function initializeApiBaseUrls() {
  if (!apiConfig.isApiConfigInitialized()) {
    console.warn("API configuration not initialized yet. Base URLs will be set when configuration is available.");
    return;
  }
  const config = apiConfig.getApiConfig();
  const baseUrl = config.backendBaseUrl;
  api.setBaseUrl$3(`${baseUrl}/accounting`);
}
apiConfig.onApiConfigReady((config) => {
  const baseUrl = config.backendBaseUrl;
  api.setBaseUrl$3(`${baseUrl}/accounting`);
});
const useFormFieldUpdater = ({
  control,
  setValue,
  fieldToUpdate,
  transformResponse,
  watch,
  fieldArrayName,
  companyField = "company_id",
  locationField = "location_id",
  departmentField = "department_id",
  customDependencies = [],
  getFieldState,
  isUpdateAccount = false
}) => {
  var _a, _b, _c;
  const { callApi } = useApi();
  const [initialState, setInitialState] = React.useState(null);
  const companyPath = fieldArrayName ? `${fieldArrayName}.${companyField}` : companyField;
  const locationPath = fieldArrayName ? `${fieldArrayName}.${locationField}` : locationField;
  const departmentPath = fieldArrayName ? `${fieldArrayName}.${departmentField}` : departmentField;
  const data = (watch == null ? void 0 : watch(`${fieldArrayName}`)) || {};
  const isDirtyCompany = (_a = getFieldState == null ? void 0 : getFieldState(companyPath)) == null ? void 0 : _a.isDirty;
  const isDirtyLocation = (_b = getFieldState == null ? void 0 : getFieldState(locationPath)) == null ? void 0 : _b.isDirty;
  const isDirtyDepartment = (_c = getFieldState == null ? void 0 : getFieldState(departmentPath)) == null ? void 0 : _c.isDirty;
  const selectedCompany = (data == null ? void 0 : data[companyField]) || null;
  const selectedLocation = (data == null ? void 0 : data[locationField]) || null;
  const selectedDepartment = (data == null ? void 0 : data[departmentField]) || null;
  React.useEffect(() => {
    if (watch && !initialState) {
      const filters = {
        [companyField]: selectedCompany,
        [locationField]: selectedLocation,
        [departmentField]: selectedDepartment
      };
      const values = {};
      Object.keys(fieldToUpdate).forEach((key) => {
        const path = fieldArrayName ? `${fieldArrayName}.${key}` : key;
        values[key] = watch(path);
      });
      setInitialState({ filters, values });
    }
  }, [watch, selectedCompany, selectedLocation, selectedDepartment, initialState, companyPath, locationPath, departmentPath, isDirtyCompany, isDirtyLocation, isDirtyDepartment]);
  const updateFields = React.useCallback((data2, forceUpdate = false) => {
    if (!setValue || !data2) return;
    const transformed = transformResponse ? transformResponse(data2) : data2;
    if (!transformed) return;
    Object.entries(fieldToUpdate).forEach(([sourceField, targetField]) => {
      const updateValue = transformed == null ? void 0 : transformed.find((i) => (i == null ? void 0 : i.config_key) == (typeof targetField == "object" ? targetField.key : targetField));
      if (updateValue !== void 0 && updateValue !== null) {
        const path = fieldArrayName ? `${fieldArrayName}.${sourceField}` : sourceField;
        if (!forceUpdate) {
          const existingValue = watch == null ? void 0 : watch(path);
          if (existingValue !== void 0 && existingValue !== null && existingValue !== "") {
            return;
          }
        }
        if (typeof targetField == "object") {
          targetField.value((updateValue == null ? void 0 : updateValue.reference_id) || (updateValue == null ? void 0 : updateValue.reference_text));
        } else {
          setValue(path, (updateValue == null ? void 0 : updateValue.reference_id) || (updateValue == null ? void 0 : updateValue.reference_text));
        }
      }
    });
  }, [setValue, fieldToUpdate, transformResponse, fieldArrayName, watch, ...customDependencies]);
  const fetchAndUpdate = React.useCallback(async () => {
    if (!selectedCompany || !initialState) return;
    const getFilterValue = (val) => {
      if (Array.isArray(val)) {
        if (val.length === 0) return null;
        const firstVal = val[0];
        if (firstVal && typeof firstVal === "object") return firstVal.id || firstVal.value || null;
        return firstVal || null;
      }
      if (val && typeof val === "object") return val.id || val.value || null;
      return val || null;
    };
    const companyId = getFilterValue(selectedCompany);
    const locationId = getFilterValue(selectedLocation);
    const departmentId = getFilterValue(selectedDepartment);
    if (!companyId || !initialState) return;
    const initialFilters = {
      companyId: getFilterValue(initialState.filters[companyField]),
      locationId: getFilterValue(initialState.filters[locationField]),
      departmentId: getFilterValue(initialState.filters[departmentField])
    };
    const isFilterChanged = initialFilters.companyId !== companyId || initialFilters.locationId !== locationId || initialFilters.departmentId !== departmentId;
    const isTargetFieldsEmpty = Object.keys(fieldToUpdate).every((key) => {
      const path = fieldArrayName ? `${fieldArrayName}.${key}` : key;
      const val = watch == null ? void 0 : watch(path);
      return val === void 0 || val === null || val === "";
    });
    if (!isFilterChanged && !isUpdateAccount && !isTargetFieldsEmpty) {
      Object.entries(initialState.values).forEach(([key, value]) => {
        const path = fieldArrayName ? `${fieldArrayName}.${key}` : key;
        setValue == null ? void 0 : setValue(path, value);
      });
      return;
    }
    const filter = `(company_id.eq=${companyId || 1}&location_id.eq=${locationId || null}&department_id.eq=${departmentId || null})`;
    const isUserChangedFilter = isDirtyCompany || isDirtyLocation || isDirtyDepartment;
    const shouldForceUpdate = isUpdateAccount ? isFilterChanged && isUserChangedFilter : isFilterChanged;
    callApi({
      apiFunc: () => api.getV1SettingsConfigurations({
        ...common.getToken(),
        filters: filter
      }),
      onSuccess: (res) => {
        var _a2;
        updateFields((_a2 = res == null ? void 0 : res.data) == null ? void 0 : _a2.configuration_list, shouldForceUpdate);
      },
      onError: (err) => {
        console.error("Error fetching accounting settings:", err);
      }
    });
  }, [selectedCompany, selectedLocation, selectedDepartment, initialState, callApi, setValue, isDirtyCompany, isDirtyLocation, isDirtyDepartment, isUpdateAccount]);
  React.useEffect(() => {
    fetchAndUpdate();
  }, [fetchAndUpdate]);
  return {
    selectedCompany,
    selectedLocation,
    selectedDepartment
  };
};
const useAccountingSetting = ({
  fieldToUpdate,
  fieldArrayName,
  companyField = "company_id",
  locationField = "location_id",
  departmentField = "department_id",
  formMethods,
  customDependencies = [],
  ...rest
}) => {
  const { setValue, control, watch, getFieldState } = formMethods || {};
  return useFormFieldUpdater({
    control,
    setValue,
    watch,
    companyField,
    locationField,
    departmentField,
    fieldToUpdate,
    fieldArrayName,
    customDependencies,
    getFieldState,
    ...rest
  });
};
exports.initializeApiBaseUrls = initializeApiBaseUrls;
exports.useAccountingSetting = useAccountingSetting;
exports.useApi = useApi;
exports.useDeepMemo = useDeepMemo;
exports.useFormFieldUpdater = useFormFieldUpdater;
exports.useLocationFilter = useLocationFilter;
exports.useMultipleLocationFilters = useMultipleLocationFilters;
exports.usePages = usePages;
exports.usePermissions = usePermissions;
//# sourceMappingURL=useAccountSetting-C2ZXqmQw.js.map
