import { createSelector } from 'reselect';
import { fromJS } from 'immutable';

// Selectors for WebPush
const selectWebPushDomain = () => (state) => state.get('webPush') || fromJS({});

const makeSelectWebPush = () => createSelector(
  selectWebPushDomain(),
  (substate) => substate.toJS()
);

const makeSelectCreateError = () => createSelector(
  selectWebPushDomain(),
  (dimensionState) => dimensionState.get('createTemplateErrorMessage') || ""
);

const makeSelectCreateTemplateInProgress = () => createSelector(
  selectWebPushDomain(),
  (substate) => substate.get('createTemplateInProgress') || false
);

const makeSelectEditTemplateInProgress = () => createSelector(
  selectWebPushDomain(),
  (substate) => substate.get('editTemplateInProgress') || false
);

const makeSelectEditError = () => createSelector(
  selectWebPushDomain(),
  (dimensionState) => dimensionState.get('editTemplateErrorMessage') || ""
);

const makeSelectUploadedAssetData = (templateType) => createSelector(
  selectWebPushDomain(),
  (substate) => {
    // Compute the key based on templateType (matches reducer logic)
    const key = templateType !== undefined
      ? `uploadedAssetData${templateType}`
      : 'uploadedAssetData';
    
    const uploadedAssetData = substate.get(key);
    
    if (!uploadedAssetData) {
      return {};
    }
    
    // Safe: handle both Immutable and plain JS values
    // If it's Immutable, convert to JS; if already plain JS, return as-is
    if (uploadedAssetData && typeof uploadedAssetData.toJS === 'function') {
      return uploadedAssetData.toJS();
    }
    
    // Already plain JS object (from reducer storing action.data directly)
    return uploadedAssetData;
  }
);

export {
  makeSelectWebPush,
  makeSelectCreateError,
  makeSelectCreateTemplateInProgress,
  makeSelectEditTemplateInProgress,
  makeSelectEditError,
  makeSelectUploadedAssetData,
};

