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

export const getMyAccountAsync = createAsyncThunk<
  // 正常時の戻り値の型
  Account,
  // 引数
  void,
  {
    // rejectした時の返却値の型
    rejectValue: {
      error: ErrorObject;
    };
  }
>("licenses/getMyAccountAsync", 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}` },
    });
    // accountIDを返す
    return getMyAccountResponse.data.account;
  } catch (e) {
    // e ⇒ errorObjectに変換"
    const error = createErrorObject(e);
    thunkApi.dispatch(
      openSnackbar({
        level: "error",
        message: getTranslationID("common.message.internalServerError"),
      })
    );
    return thunkApi.rejectWithValue({ error });
  }
});

// サービスAPIからアカウント情報をもらう
export const getPartnerLicenseAsync = createAsyncThunk<
  // 正常時の戻り値の型
  GetPartnerLicensesResponse,
  // 引数
  {
    limit: number;
    offset: number;
    accountId: number | undefined;
  },
  {
    // rejectした時の返却値の型
    rejectValue: {
      error: ErrorObject;
    };
  }
>("licenses/getPartnerLicenseAsync", 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}` },
    });

    const accountId =
      args.accountId ?? getMyAccountResponse.data.account.accountId;

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

    thunkApi.dispatch(
      openSnackbar({
        level: "error",
        message: getTranslationID("common.message.internalServerError"),
      })
    );

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