import * as log from 'loglevel';

import {defineStore} from 'pinia'
import {itGet, itPost} from '@/fetchHelpers';
import {useAppStore} from '@/stores/app';
// typed state https://stackoverflow.com/questions/71012513/when-using-pinia-and-typescript-how-do-you-use-an-action-to-set-the-state

export type UserState = {
  first_name: string,
  last_name: string,
  email: string;
  username: string,
  avatar_url: string,
  loggedIn: boolean;
}

export const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    email: '',
    first_name: '',
    last_name: '',
    username: '',
    avatar_url: '',
    loggedIn: false
  } as UserState),
  getters: {
    getFullName(): string {
      return `${this.first_name} ${this.last_name}`.trim();
    },
  },
  actions: {
    handleLogin(username: string, password: string, next='/') {
      if (username && password) {
        itPost('/core/login/', {
          username,
          password,
        }).then((data) => {
          this.$state = data;
          this.loggedIn = true;
          log.debug(`redirect to ${next}`);
          window.location.href = next;
        }).catch(() => {
          this.loggedIn = false;
          alert('Login failed');
        });
      }
    },
    fetchUser() {
      const appStore = useAppStore();
      itGet('/api/core/me/').then((data) => {
        this.$state = data;
        this.loggedIn = true;
        appStore.userLoaded = true;
      }).catch(() => {
        this.loggedIn = false;
        appStore.userLoaded = true;
      })
    }
  }
})
