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

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

  try {
    await accountApi.createPartnerAccount(createPartnerAccountRequest, {
      headers: { authorization: `Bearer ${accessToken}` },
    });
    thunkApi.dispatch(
      openSnackbar({
        level: "info",
        message: getTranslationID(
          "addPartnerAccountPopupPage.message.addAccountSuccess"
        ),
      })
    );
    return {};
  } catch (e) {
    const error = createErrorObject(e);
    if (error.code === "E010301") {
      thunkApi.dispatch(
        openSnackbar({
          level: "error",
          message: getTranslationID(
            "addPartnerAccountPopupPage.message.emailConflictError"
          ),
        })
      );
    } else {
      thunkApi.dispatch(
        openSnackbar({
          level: "error",
          message: getTranslationID("common.message.internalServerError"),
        })
      );
    }

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