import { createAsyncThunk } from "@reduxjs/toolkit";
import type { RootState } from "app/store";
import { ErrorObject, createErrorObject } from "common/errors";
import { getTranslationID } from "translation";
import { closeSnackbar, openSnackbar } from "features/ui/uiSlice";
import { AccountsApi, CreateAccountRequest } from "../../api/api";
import { Configuration } from "../../api/configuration";

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

  try {
    thunkApi.dispatch(closeSnackbar());
    await accountApi.createAccount(createAccountRequest);

    thunkApi.dispatch(closeSnackbar());

    return {};
  } catch (e) {
    const error = createErrorObject(e);
    if (error.code === "E010301") {
      thunkApi.dispatch(
        openSnackbar({
          level: "error",
          message: getTranslationID(
            "signupConfirmPage.message.emailConflictError"
          ),
        })
      );
    } else {
      thunkApi.dispatch(
        openSnackbar({
          level: "error",
          message: getTranslationID("common.message.internalServerError"),
        })
      );
    }

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