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

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

  try {
    const { data } = await authApi.token({
      idToken,
      type: "web",
    });
    // アクセストークン・リフレッシュトークンをlocalStorageに保存
    thunkApi.dispatch(
      setToken({
        accessToken: data.accessToken,
        refreshToken: data.refreshToken,
      })
    );

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