import { gql, useMutation, PureQueryOptions } from '@apollo/client';
import { FRAGMENT_FULL_PROJECT, FRAGMENT_FULL_TASK, FRAGMENT_FULL_PROJECT_PARAMS } from '../fragments/project';
import { QUERY_PROJECTS } from '../queries/project';

export const MUTATION_CREATE_PROJECT = gql`
mutation createProject($changes: CreateProjectChanges!) {
  createProject(changes: $changes) {
    ...FullProject
  }
}
${FRAGMENT_FULL_PROJECT}
`;

export function useProjectCreateMutation() {
  return useMutation(MUTATION_CREATE_PROJECT);
}

export const MUTATION_UPDATE_PROJECT_TITLE = gql`
mutation updateProjectTitle($projectId: ID!, $title: String!) {
  updateProjectTitle(projectId: $projectId, title: $title) {
    ...FullProject
  }
}
${FRAGMENT_FULL_PROJECT}
`;

export function useUpdateProjectTitleMutation() {
  return useMutation(MUTATION_UPDATE_PROJECT_TITLE, {
    refetchQueries: ({ variables }: PureQueryOptions) => {
      return [
        { query: QUERY_PROJECTS, variables: { filters: { ids: [ variables.projectId ] } }},
      ];
    }
  });
}

export const MUTATION_ADD_PROJECT_TASK = gql`
mutation addProjectTask($projectId: ID!, $changes: ProjectTaskChanges!) {
  addProjectTask(projectId: $projectId, changes: $changes) {
    ...FullTask
  }
}
${FRAGMENT_FULL_TASK}
`;

export function useAddProjectTaskMutation() {
  return useMutation(MUTATION_ADD_PROJECT_TASK);
}

export const MUTATION_UPDATE_PROJECT_TASK = gql`
mutation updateProjectTask($projectId: ID!, $taskId: ID!, $changes: ProjectTaskChanges!) {
  updateProjectTask(projectId: $projectId, taskId: $taskId, changes: $changes) {
    ...FullTask
  }
}
${FRAGMENT_FULL_TASK}
`;

export function useUpdateProjectTaskMutation() {
  return useMutation(MUTATION_UPDATE_PROJECT_TASK);
}

export const MUTATION_REMOVE_PROJECT_TASK = gql`
mutation removeProjectTask($projectId: ID!, $taskId: ID!) {
  removeProjectTask(projectId: $projectId, taskId: $taskId)
}
`;

export function useRemoveProjectTaskMutation() {
  return useMutation(MUTATION_REMOVE_PROJECT_TASK);
}

export const MUTATION_UPDATE_PROJECT_PARAMS = gql`
mutation updateProjectParams($projectId: ID!, $changes: ProjectParamsChanges!) {
  updateProjectParams(projectId: $projectId, changes: $changes) {
    ...FullProjectParams
  }
}
${FRAGMENT_FULL_PROJECT_PARAMS}
`;

export function useUpdateProjectParamsMutation() {
  return useMutation(MUTATION_UPDATE_PROJECT_PARAMS);
}
