<template>
  <div class="start-registration-register">
    <GlobalForm
      endpoint="registration/register"
      :form-id="formId"
      :schema="schema"
      :error-log-callback="onError"
      :reset-on-success="false"
      @onRequestSuccess="requestCallback"
    >
      <template #fields>
        <BaseText>{{ $_tr('introduction') }}</BaseText>

        <InputPassword
          model-name="password"
          :form-id="formId"
          :rules="['required']"
          :label="$_tr('fields.password')"
          @onDataChange="onDataChange"
        />

        <InputPassword
          model-name="password_confirmation"
          :form-id="formId"
          :rules="['required']"
          :label="$_tr('fields.passwordConfirmation')"
        />

        <InputHidden
          model-name="email"
          :form-id="formId"
          :default-value="urlQueries.email"
        />

        <InputHidden
          model-name="signature"
          :form-id="formId"
          :default-value="urlQueries.signature"
        />

        <InputHidden
          model-name="expires"
          :form-id="formId"
          :default-value="urlQueries.expires"
        />

        <InputHidden
          model-name="langcode"
          :form-id="formId"
          :default-value="language"
        />

        <p class="register-users__text password">{{ $_tr('infos') }}</p>
      </template>

      <template #submitForm>
        <input
          type="submit"
          class="btn"
          :value="$_tr('common.actions.validate')"
        />
      </template>
    </GlobalForm>
  </div>
</template>

<script>
import * as yup from 'yup'

import { BaseText } from 'inside-collection/atoms'

import GlobalForm from '@inside-forms/displays/GlobalForm'
import InputPassword from '@inside-forms/displays/sub-components/fields/InputPassword'
import InputHidden from '@inside-forms/displays/sub-components/fields/InputHidden'

import { http } from '@inside-library/helpers/Http'
import logAs from '@inside-auth/helpers/log-as'

import GetNavigatorLanguage from '../../../mixins/get-navigator-language'
import registerURLs from '../../../mixins/register-urls'

export default {
  name: 'start-registration-register',
  $_i18nRootPath: 'customs.START_REGISTRATION_REGISTER',
  components: {
    BaseText,
    GlobalForm,
    InputPassword,
    InputHidden
  },
  mixins: [GetNavigatorLanguage],
  data() {
    return {
      formId: 'password_register',
      password: '',
      urlQueries: {}
    }
  },
  computed: {
    schema() {
      return yup.object().shape({
        password: yup
          .string()
          .min(6, this.$tc('forms.FIELDS.ERRORS.password', [6]))
          .matches(/^(?!.*[,\|]).*$/, this.$_tr('forms.FIELDS.ERRORS.regex'))
          .required(this.$_tr('forms.FIELDS.ERRORS.required')),
        password_confirmation: yup
          .string()
          .oneOf(
            [yup.ref('password'), null],
            this.$_tr('forms.FIELDS.ERRORS.mismatch')
          )
          .required(this.$_tr('forms.FIELDS.ERRORS.required'))
      })
    }
  },
  beforeMount() {
    this.urlQueries = {
      ...this.$route.query,
      langcode: this.language
    }

    this.checkSignatureAvailability()
  },
  methods: {
    onDataChange({ value }) {
      this.password = value
    },
    async checkSignatureAvailability() {
      try {
        await http.get('registration/validate', {
          ...this.urlQueries
        })
      } catch (err) {
        this.$router.push(registerURLs['check-in'])
      }
    },
    async requestCallback() {
      /*
       * Auto login the user
       */
      const { data } = await http.post('authentication/login', {
        email: this.urlQueries.email,
        password: this.password
      })

      const succeed = await logAs({
        token: data.api_token,
        uuid: data.uuid,
        permissions: data.permissions,
        langcode: data.langcode,
        email: data.email
      })

      this.isSucceed = succeed

      if (succeed) {
        window.location.href = registerURLs['complete-profile']
      }
    },
    onError(err) {
      return Object.values(err)
        .flatMap(item => item)
        .join('')
    }
  }
}
</script>

<style lang="scss">
@use '@inside-library/styles/mixins/partials/common-mixin' as *;

.register-users__text {
  &.password {
    margin-top: var(--spacing-m);
    color: var(--color-grey);
    font-style: italic;
  }
}
</style>
