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', // password | refresh_token
      username: '',
      password: '',
      refresh_token: ''
    },
    isInvalid: false,
    userData: {},
    // expired: new Date().setMonth(6), // 設定 Refresh Token 的到期日為半年後
  }),
  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 accessToken = response.data.access_token;
        const refreshToken = response.data.refresh_token;

        // 將 token 儲存在 cookie
        document.cookie = `luciaToken=${accessToken}`;
        // document.cookie = `luciaRefreshToken=${refreshToken};expires=${new Date(this.expired)};`;

        this.$router.push('/files');
      } catch(error) {
        this.isInvalid = true;
      };
    },
    /**
     * Refresh Token
     */
    async refreshTokenLogin() {
      const api = '/api/oauth/token';
      const refreshToken = document.cookie.replace(/(?:(?:^|.*;\s*)luciaRefreshToken\s*\=\s*([^;]*).*$)|^.*$/, "$1");
      console.log(document.cookie);


      this.auth.grant_type = 'refresh_token';
      this.auth.refresh_token = refreshToken;

      // try {
      //   const response = await axios.post(api, this.auth, config);
      //   const newAccessToken = response.data.access_token;
      //   const newRefreshToken = response.data.refresh_token;

      //   document.cookie = `luciaToken=${newAccessToken}`;
      //   document.cookie = `luciaRefreshToken=${newRefreshToken};expires=${this.expired}`;

      //   defaults.headers.common['Authorization'] = `Bearer ${newAccessToken}`;
      // } catch(error) {
      //   this.$router.push('/login');
      // }
    },
    /**
     * 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');
      };
    },
  }
});
