import { computed } from 'vue';
import { useRoute } from 'vue-router';
import { OBJECT_CONTEXT_QUERY_KEY, getObjectContextDomainConfigByPath } from '@/constants/object-context';
import { useObjectContextStore } from '@/store/modules/object-context';
import { normalizeCurrentProductSummary, resolveObjectIdFromQuery } from './product-context-shared';

export function useCurrentProduct() {
  const route = useRoute();
  const objectContextStore = useObjectContextStore();
  const isProductDomainRoute = computed(() => getObjectContextDomainConfigByPath(route.path)?.domainKey === 'product');

  const currentObjectId = computed(() => {
    if (!isProductDomainRoute.value) {
      return '';
    }

    return resolveObjectIdFromQuery(route.query[OBJECT_CONTEXT_QUERY_KEY], objectContextStore.objectId);
  });

  const currentProduct = computed(() => {
    if (!isProductDomainRoute.value) {
      return null;
    }

    return normalizeCurrentProductSummary(objectContextStore.objectSummary, objectContextStore.objectName);
  });

  return {
    currentObjectId,
    currentProduct
  };
}
