import { defineStore } from "pinia";
import axios from 'axios';

export default defineStore('loginStore', {
  // data, methods, computed
  // state, actions, getters
  state: () => ({
    auth: {
      username: '',
      password: '',
    },
    isInvalid: false,
    userData: {},
  }),

  // 讓元件取用相關的資料狀態
  getters: {
  },

  actions: {
    /**
     * fetch Login For Access Token api
     */
    async signIn() {
      const api = '/api/oauth/token';
      const config = {
        headers: {
          // http post 預設的 url 編碼，非 json 格式
          'Content-Type':'application/x-www-form-urlencoded',
        },
      };

      try {
        const response = await axios.post(api, this.auth, config);

        if(response.status === 200){
          // 將 token 儲存在 cookie
          const token = response.data.access_token;

          document.cookie = `luciaToken=${token}`;
          this.$router.push('/files');
        }
      } catch(error) {
        console.dir(error); // safari 測試
        this.isInvalid = true;
      };
    },
    /**
     * log out, tooken expired
     */
    logOut() {
      let isCookie = document.cookie.split(';').some(c => c.trim().startsWith('luciaToken='));
      let expires = new Date();
      expires.setTime(expires.getTime() - 60000);

      if(isCookie){
      document.cookie = `luciaToken=; expires=${expires.toGMTString()}`;
      this.$router.push('/login');
      }
    },
    /**
     * get user detail for 'my-account' api
     */
    async getUserData() {
      const api = '/api/my-account';

      try {
        const response = await axios.get(api);

        this.userData = response.data;
      } catch(error) {
        console.dir(error); // safari 測試
      };
    },
    /**
     * check login for 'my-account' api
     */
    async checkLogin() {
      const api = '/api/my-account';

      try {
        const response = await axios.get(api);
        if(response.status !== 200) this.$router.push('/login');
      } catch(error) {
        console.dir(error); // safari 測試
        this.$router.push('/login');
      };
    },
  }
})
