import { createAsyncThunk } from "@reduxjs/toolkit";
import type { RootState } from "app/store";
import { UsersApi } from "../../api/api";
import { Configuration } from "../../api/configuration";
import { ErrorObject, createErrorObject } from "../../common/errors";

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

  try {
    await usersApi.confirmUser({ token: jwt });
    return {};
  } catch (e) {
    // e ⇒ errorObjectに変換
    const error = createErrorObject(e);

    return thunkApi.rejectWithValue({ error });
  }
});

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

  try {
    await usersApi.confirmUserAndInitPassword({ token: jwt });
    return {};
  } catch (e) {
    // e ⇒ errorObjectに変換
    const error = createErrorObject(e);

    return thunkApi.rejectWithValue({ error });
  }
});
