import { defineStore } from "pinia";
import axios from 'axios';
import apiError from '@/module/apiError.js';

export default defineStore('loginStore', {
  // data, methods, computed
  // state, actions, getters
  state: () => ({
    auth: {
      grant_type: 'password',
      username: '',
      password: '',
    },
    isInvalid: false,
    userData: {},
  }),
  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);
        const token = response.data.access_token;
        // 將 token 儲存在 cookie
        document.cookie = `luciaToken=${token};`;
        // // 取得當前日期
        // const currentDate = new Date();
        // // 設定 cookie 的過期日期為一天後
        // const expirationDate = new Date();
        // expirationDate.setDate(currentDate.getDate() + 1);
        // // 格式化過期日期為 Cookie 格式
        // const expires = expirationDate.toUTCString();
        this.$router.push('/files');
      } catch(error) {
        this.isInvalid = true;
      };
    },
    /**
     * Logout, tooken expired
     */
    logOut() {
      delete axios.defaults.headers.common["Authorization"];
      document.cookie = 'luciaToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC;';
      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) {
        apiError(error, 'Failed to load the Map.');
      };
    },
    /**
     * check login for 'my-account' api
     */
    async checkLogin() {
      const api = '/api/my-account';

      try {
        const response = await axios.get(api);
      } catch(error) {
        this.$router.push('/login');
      };
    },
  }
});
