import UPDATE_PROJECT_SHARED_STATE_MUTATION from '@/graphql/gql/mutations/updateProjectSharedState.gql';
import PROJECT_QUERY from '@/graphql/gql/queries/projectQuery.gql';
import log from 'loglevel';

export default {
  methods: {
    updateProjectShareState(slug, shared) {
      const input = {
        slug,
        shared,
      };
      log.debug('updateProjectShareState', input);
      this.$apollo.mutate({
        mutation: UPDATE_PROJECT_SHARED_STATE_MUTATION,
        variables: {
          input,
        },
        update: (
          store,
          {
            data: {
              updateProjectSharedState: { shared: final, errors },
            },
          }
        ) => {
          if (!errors) {
            const query = PROJECT_QUERY;
            const variables = {
              slug,
            };

            const { project } = store.readQuery({ query, variables });
            log.debug(`updating project ${project.id} ${project.title}`);

            if (project) {
              const data = {
                project: {
                  ...project,
                  final,
                },
              };
              store.writeQuery({ query, variables, data });
            }
          }
        },
      });
    },
  },
};
