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 { resolveObjectIdFromQuery } from '@/views/product/shared/product-context-shared';

/**
 * 获取当前项目上下文
 */
export function useCurrentProject() {
  const route = useRoute();
  const objectContextStore = useObjectContextStore();
  const isProjectDomainRoute = computed(() => getObjectContextDomainConfigByPath(route.path)?.domainKey === 'project');

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

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

  const currentProject = computed(() => {
    if (!isProjectDomainRoute.value) {
      return null;
    }

    const summary = objectContextStore.objectSummary;

    if (!summary) {
      return null;
    }

    return ((summary as unknown as Api.Project.ProjectContext).currentProject || null) as
      | Api.Project.ProjectContext['currentProject']
      | null;
  });

  const currentRole = computed(() => {
    if (!isProjectDomainRoute.value) {
      return null;
    }

    const summary = objectContextStore.objectSummary;

    if (!summary) {
      return null;
    }

    return (summary as unknown as Api.Project.ProjectContext).currentRole || null;
  });

  const isGuest = computed(() => currentRole.value?.guestFlag ?? true);

  return {
    currentObjectId,
    currentProject,
    currentRole,
    isGuest
  };
}
