<template>
  <div>AuthPage</div>

  <v-form v-model="valid" @submit.prevent="login">
    <v-container>
      <v-row>
        <v-col
            cols="12"
            md="6"
        >
          <v-text-field
              v-model="username"
              :rules="usernameRules"
              label="Имя пользователя"
              required
          ></v-text-field>
        </v-col>
        <v-col
            cols="12"
            md="6"
        >
          <v-text-field
              v-model="password"
              :counter="10"
              :rules="passwordRules"
              label="Пароль"
              type="password"
              required
          ></v-text-field>

        </v-col>
      </v-row>
      <v-row>
        <v-col
            cols="12"
            md="12"
            class="text-right"
        >
          <v-btn
              :disabled="!valid"
              color="success"
              class="mr-4"
              type="submit"
              :loading="loading"
          >
            Войти
          </v-btn>
        </v-col>
      </v-row>
    </v-container>
  </v-form>
</template>

<script setup>
import {ref} from "vue";
import {useAxios} from "../composables/useAxios";
import {useAuth} from "vue-auth3";

const {client} = useAxios();
const auth = useAuth();

const valid = ref(false);
const loading = ref(false);

const password = ref('123123123');
const passwordRules = [
  value => {
    if (value) return true

    return 'Пароль обязателен.'
  },
  value => {
    if (value?.length >= 8) return true

    return 'Пароль должен быть не менее 8 символов.'
  },
];

const username = ref('test');
const usernameRules = [
  value => {
    if (value) return true

    return 'Введите имя пользователя.'
  }
]


async function login() {
  loading.value = true

  try {

    console.log(auth)

    const { data } = await auth.login({
      data: {
        username: username.value,
        password: password.value,
      },
      redirect: { name: "home" },
      staySignedIn: true,
      fetchUser: true,
    })

    client.defaults.headers.common['Authorization'] = `Bearer ${data.token}`

  } catch (e) {
    console.log(e)
    loading.value = false
  }

  loading.value = false
}

console.log(import.meta.env);
</script>