import MODULE_DETAILS_QUERY from './gql/queries/modules/moduleDetailsQuery.gql';
import ME_QUERY from './gql/queries/meQuery.gql';
import { useRoute } from 'vue-router';
import { computed } from 'vue';
import { useQuery } from '@vue/apollo-composable';
import { graphql } from '@/__generated__/gql';

export function moduleQuery() {
  return {
    query: MODULE_DETAILS_QUERY,
    variables: {
      slug: this.$route.params.slug,
    },
  };
}

const getModule = () => {
  const route = useRoute();
  const query = graphql(MODULE_DETAILS_QUERY, {
    slug: route.params.slug,
  });
  const { result } = useQuery(query);
  const module = computed(() => result.value?.module || {});

  return { module };
};

export function meQuery() {
  return {
    query: ME_QUERY,
  };
}

graphql(`
  fragment SchoolClassParts on SchoolClassNode {
    id
    name
  }
`);
graphql(`
  fragment UserParts on PrivateUserNode {
    id
    pk
    username
    email
    firstName
    lastName
    avatarUrl
    expiryDate
    readOnly
    lastModuleLevel {
      id
      name
      filterAttributeType
    }
    lastModule {
      id
      slug
    }
    lastTopic {
      id
      slug
    }
    selectedClass {
      id
      readOnly
    }
    recentModules(orderBy: "-visited") {
      edges {
        node {
          ...ModuleParts
        }
      }
    }
    schoolClasses {
      ...SchoolClassParts
    }
  }
`);
graphql(`
  fragment TeamParts on TeamNode {
    name
    code
    id
    members {
      firstName
      lastName
      id
      isMe
    }
  }
`);
graphql(`
  fragment ModuleParts on ModuleNode {
    id
    title
    metaTitle
    teaser
    intro
    slug
    heroImage
    heroSource
    solutionsEnabled
    highlights {
      ...HighlightParts
    }
    language
    inEditMode @client
    level {
      id
      name
    }
    category {
      id
      name
    }
    topic {
      slug
      title
    }
    bookmark {
      note {
        id
        text
      }
    }
  }
`);

const getMe = () => {
  const query = graphql(`
    query MeQuery {
      me {
        ...UserParts
        team {
          ...TeamParts
        }
        isTeacher
        permissions
        onboardingVisited
      }
    }
  `);
  const { result } = useQuery(query);
  const me = computed(() => result.value?.me || { isTeacher: false });

  return { me };
};

export { getModule, getMe };
