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

export const getLicenseOrderHistoriesAsync = createAsyncThunk<
  // 正常時の戻り値の型
  GetOrderHistoriesResponce,
  {
    // パラメータ
    limit: number;
    offset: number;
  },
  {
    // rejectした時の返却値の型
    rejectValue: {
      error: ErrorObject;
    };
  }
>("licenses/licenseOrderHisotyAsync", async (args, thunkApi) => {
  const { limit, offset } = args;
  // 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 { selectedRow } = state.partnerLicense.apps;
    let accountId = 0;
    // 他の画面から指定されていない場合はログインアカウントのidを取得する
    if (!selectedRow) {
      const getMyAccountResponse = await accountsApi.getMyAccount({
        headers: { authorization: `Bearer ${accessToken}` },
      });
      // accountIDを返す
      accountId = getMyAccountResponse.data.account.accountId;
    } else {
      accountId = selectedRow.accountId;
    }

    const res = await accountsApi.getOrderHistories(
      {
        limit,
        offset,
        accountId,
      },
      {
        headers: { authorization: `Bearer ${accessToken}` },
      }
    );
    return res.data;
  } catch (e) {
    // e ⇒ errorObjectに変換"
    const error = createErrorObject(e);
    thunkApi.dispatch(
      openSnackbar({
        level: "error",
        message: getTranslationID("common.message.internalServerError"),
      })
    );
    return thunkApi.rejectWithValue({ error });
  }
});
