import { createAsyncThunk } from "@reduxjs/toolkit";
import { RootState } from "app/store";
import { AuthApi } from "../../api/api";
import { Configuration } from "../../api/configuration";
import { setToken } from "./authSlice";

export const updateTokenAsync = createAsyncThunk<
  {
    /* Empty Object */
  },
  void,
  {
    // rejectした時の返却値の型
    rejectValue: {
      /* Empty Object */
    };
  }
>("auth/updateTokenAsync", async (args, thunkApi) => {
  // apiのConfigurationを取得する
  const { getState } = thunkApi;
  const state = getState() as RootState;
  const { configuration, refreshToken } = state.auth;
  const config = new Configuration(configuration);
  const authApi = new AuthApi(config);

  try {
    const { data } = await authApi.accessToken({
      headers: { authorization: `Bearer ${refreshToken}` },
    });
    // アクセストークン・リフレッシュトークンをlocalStorageに保存
    thunkApi.dispatch(
      setToken({
        accessToken: data.accessToken,
        refreshToken: state.auth.refreshToken,
      })
    );

    return {};
  } catch (e) {
    return thunkApi.rejectWithValue({});
  }
});
