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

export const getLicenseSummaryAsync = createAsyncThunk<
  // 正常時の戻り値の型
  GetLicenseSummaryResponse,
  // 引数
  void,
  {
    // rejectした時の返却値の型
    rejectValue: {
      error: ErrorObject;
    };
  }
>("licenses/getLicenseSummaryAsync", async (args, thunkApi) => {
  // apiのConfigurationを取得する
  const { getState } = thunkApi;
  const state = getState() as RootState;
  const { configuration, accessToken } = state.auth;
  const config = new Configuration(configuration);
  const accountsApi = new AccountsApi(config);

  try {
    const getMyAccountResponse = await accountsApi.getMyAccount({
      headers: { authorization: `Bearer ${accessToken}` },
    });

    // 自分のアカウントID取得、取得したアカウントIDを使用して表示情報を取得する
    const { accountId } = getMyAccountResponse.data.account;

    const getLicenseSummaryResponse = await accountsApi.getLicenseSummary(
      { accountId },
      {
        headers: { authorization: `Bearer ${accessToken}` },
      }
    );
    return getLicenseSummaryResponse.data;
  } catch (e) {
    // e ⇒ errorObjectに変換"
    const error = createErrorObject(e);

    const errorMessage = getTranslationID("common.message.internalServerError");

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

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