<template>
  <join-form
    :value="name"
    class="create-team"
    title="Team erfassen"
    ok-text="Team erfassen"
    label-text="Name"
    :error="error"
    cancel-text="Abbrechen"
    @input="updateName"
    @cancel="cancel"
    @confirm="createTeam"
  />
</template>

<script>
import JoinForm from '@/components/profile/JoinForm.vue';

import CREATE_TEAM_MUTATION from '@/graphql/gql/mutations/createTeam.gql';
import { MY_TEAM } from '@/router/me.names';
import addTeam from '@/helpers/add-team';

export default {
  components: {
    JoinForm,
  },

  data: () => ({
    name: '',
    error: '',
  }),

  methods: {
    updateName(event) {
      this.name = event.target.value;
      this.error = '';
    },
    createTeam(name) {
      this.$apollo.mutate({
        mutation: CREATE_TEAM_MUTATION,
        variables: {
          input: {
            name,
          },
        },
        update: (
          store,
          {
            data: {
              createTeam: { result },
            },
          }
        ) => {
          if (result.__typename === 'DuplicateName') {
            this.error = result.reason;
          } else {
            addTeam(store, result);

            this.$router.push({
              name: MY_TEAM,
            });
          }
        },
      });
    },
    cancel() {
      this.$router.go(-1);
    },
  },
};
</script>
