import { ref } from 'vue';
import type { Ref } from 'vue';
import { defineStore } from 'pinia';
import api from '@/api/index';
import { User } from '@/types/user';
import { $axios } from '@/plugins/axios';

type AuthForm = {
  email: string;
  password: string;
};

$axios.interceptors.response.use((response) => {
  if (response.status === 401) {
    location.pathname = '/auth';
  }
  return response;
});

export const useAuthStore = defineStore('auth', () => {
  const $router = useRouter();

  const loggedIn: Ref<boolean> = ref(false);
  const user: Ref<User | undefined> = ref(undefined);
  const err: Ref<string> = ref('');
  const form: Ref<AuthForm> = ref({
    email: '',
    password: '',
  });

  //
  // MARK: Log in
  //
  const doAuth = async (): Promise<void> => {
    const [_, e] = await api.auth.login(form.value.email, form.value.password);
    if (e && typeof e === 'string') {
      err.value = e;
    }
  };

  //
  // MARK: Get authorized user data
  //
  const getMe = async (): Promise<void> => {
    const [res, e] = await api.auth.getMe();
    if (e && typeof e === 'string') {
      // TODO e
      // $notifications.show(t('notifies.oops'), 'error');
      console.error('TODO:', e);
      logout();
      return;
    }

    console.log('res', res?.data);
    if (res?.data?.data !== null) {
      user.value = res?.data?.data;
      loggedIn.value = true;
    } else {
      // TODO notify user not found
      console.error('TODO: USER NOT FOUND');
    }
  };

  //
  // MARK: Log out
  //
  const logout = async (): Promise<void> => {
    const [_, e] = await api.auth.logout();
    if (e && typeof e === 'string') {
      // TODO notify
      console.error('TODO:', e);
    }

    loggedIn.value = false;
    user.value = undefined;
    $router.push('/auth');
  };

  return {
    loggedIn,
    user,
    form,
    err,
    doAuth,
    getMe,
    logout,
  };
});
