import { gql, useQuery, useMutation, FetchResult } from '@apollo/client';
import { QUERY_WORKGROUP } from '../queries/workgroups';
import { QUERY_IS_AUTHORIZED } from '../queries/authorization';

export const MUTATION_UPDATE_WORKGROUP = gql`
mutation updateWorkgroup($workgroupId: ID!, $changes: WorkgroupChanges!) {
  updateWorkgroup(workgroupId: $workgroupId, changes: $changes) {
    id,
    name,
    createdAt,
    closedAt,
    members {
      id,
      name,
      email
    }
  }
}`;

export function useUpdateWorkgroupMutation() {
  return useMutation(MUTATION_UPDATE_WORKGROUP);
}

export const MUTATION_CREATE_WORKGROUP = gql`
mutation createWorkgroup($changes: WorkgroupChanges!) {
  createWorkgroup(changes: $changes) {
    id,
    name,
    createdAt,
    closedAt,
    members {
      id,
      name,
      email
    }
  }
}`;

export function useCreateWorkgroupMutation() {
  return useMutation(MUTATION_CREATE_WORKGROUP, {
    refetchQueries: [{query: QUERY_WORKGROUP}],
  });
}

export const MUTATION_JOIN_WORKGROUP = gql`
mutation joinWorkgroup($workgroupId: ID!) {
  joinWorkgroup(workgroupId: $workgroupId) {
    id,
    name,
    createdAt,
    closedAt,
    members {
      id,
      name,
      email
    }
  }
}`;

export function useJoinWorkgroupMutation() {
  return useMutation(MUTATION_JOIN_WORKGROUP, {
    refetchQueries: ({ data }: FetchResult) => {
      return [{
        query: QUERY_IS_AUTHORIZED,
        variables: {
          action: 'update',
          object: {
            workgroupId: data.joinWorkgroup.id,
          }
        }
      }]
    }
  });
}

const MUTATION_LEAVE_WORKGROUP = gql`
mutation leaveWorkgroup($workgroupId: ID!) {
  leaveWorkgroup(workgroupId: $workgroupId) {
    id,
    name,
    createdAt,
    closedAt,
    members {
      id,
      name,
      email
    }
  }
}`;

export function useLeaveWorkgroupMutation() {
  return useMutation(MUTATION_LEAVE_WORKGROUP, {
    refetchQueries: ({ data }: FetchResult) => {
      return [{
        query: QUERY_WORKGROUP,
        variables: {
          filter: {
            ids: [data.leaveWorkgroup.id],
          }
        }
      },
      {
        query: QUERY_IS_AUTHORIZED,
        variables: {
          action: 'update',
          object: {
            workgroupId: data.leaveWorkgroup.id,
          }
        }
      }]
    }
  });
}

const MUTATION_CLOSE_WORKGROUP = gql`
mutation closeWorkgroup($workgroupId: ID!) {
  closeWorkgroup(workgroupId: $workgroupId) {
    id,
    name,
    createdAt,
    closedAt,
    members {
      id,
      name,
      email
    }
  }
}`;

export function useCloseWorkgroupMutation() {
  return useMutation(MUTATION_CLOSE_WORKGROUP);
}