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 { getAccessToken } from "features/auth";
import {
  AccountsApi,
  CreatePartnerAccountRequest,
  GetPartnersResponse,
} 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 } = state.auth;
  const accessToken = getAccessToken(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 });
  }
});

// パートナー一覧取得APIからパートナーのアカウント情報をもらう
export const getPartnerInfoAsync = createAsyncThunk<
  // 正常時の戻り値の型
  GetPartnersResponse,
  {
    // パラメータ
    limit: number;
    offset: number;
  },
  {
    // rejectした時の返却値の型
    rejectValue: {
      error: ErrorObject;
    };
  }
>("partner/getPartnerInfoAsync", async (args, thunkApi) => {
  const { limit, offset } = args;
  const { getState } = thunkApi;
  const state = getState() as RootState;
  const { configuration } = state.auth;
  const accessToken = getAccessToken(state.auth);
  const config = new Configuration(configuration);
  const accountsApi = new AccountsApi(config);

  try {
    const res = await accountsApi.getPartners(limit, offset, {
      headers: { authorization: `Bearer ${accessToken}` },
    });
    const ret = {
      partners: res.data.partners,
      total: res.data.total,
    };
    return ret;
  } catch (e) {
    const error = createErrorObject(e);
    const errorMessage = getTranslationID("common.message.internalServerError");

    thunkApi.dispatch(
      openSnackbar({
        level: "error",
        message: errorMessage,
      })
    );

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