import { createAsyncThunk } from '@reduxjs/toolkit';
import {StorageKeys} from '../../globalConstants.js'
import {request} from '../../utils/request.js';
import {removeToken, setToken} from '../../utils/auth.js';

/** 用户登录接口 */
export const login = createAsyncThunk(
  'app/login',
  async ({ params, resolve }) => {
    const {code,data} = await request({
      url: '/auth/user/login',
      method: 'POST',
      data: params,
    });
    if (code===200){
      localStorage.setItem(StorageKeys.AuthorizationToken, data);
      setToken(data);
      resolve && resolve();
    }
    return data;
  },
);

/** 获取当前用户信息 */
export const getCurrentUser = createAsyncThunk(
  'app/getCurrentUser',
  async () => {
    const { data } = await request('/auth/user/getCurrentUser' );
    localStorage.setItem(StorageKeys.LoggedInUser, JSON.stringify(data));
    return data;
  },
);

/** 退出登录 */
export const logout = createAsyncThunk(
  'app/logout',
    async resolve => {
      try {
        removeToken();
        localStorage.removeItem(StorageKeys.LoggedInUser);
        resolve && resolve();
        return void 0;
      } catch (error) {
        throw error;
      }
    },
);

/** */
export const setCurrentUser = createAsyncThunk(
  'app/setCurrentUser',
    async () => {
      try {
        const loggedInUser = localStorage.getItem(StorageKeys.LoggedInUser);
        return JSON.parse(loggedInUser);
      } catch (error) {
        throw error;
      }
    },
);