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

export const activateCardLicenseAsync = createAsyncThunk<
  {
    /* Empty Object */
  },
  {
    // パラメータ
    cardLicenseKey: string;
  },
  {
    // rejectした時の返却値の型s
    rejectValue: {
      error: ErrorObject;
    };
  }
>("licenses/activateCardLicenseAsync", async (args, thunkApi) => {
  const { cardLicenseKey } = args;

  // apiのConfigurationを取得する
  const { getState } = thunkApi;
  const state = getState() as RootState;
  const { configuration, accessToken } = state.auth;
  const config = new Configuration(configuration);
  const licensesApi = new LicensesApi(config);

  try {
    await licensesApi.activateCardLicenses(
      {
        cardLicenseKey,
      },
      {
        headers: { authorization: `Bearer ${accessToken}` },
      }
    );
    thunkApi.dispatch(
      openSnackbar({
        level: "info",
        message: getTranslationID("common.message.success"),
      })
    );
    return {};
  } catch (e) {
    // e ⇒ errorObjectに変換"
    const error = createErrorObject(e);

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

    if (error.code === "E010801") {
      errorMessage = getTranslationID(
        "cardLicenseActivatePopupPage.message.LicenseKeyNotExistError"
      );
    } else if (error.code === "E010802") {
      errorMessage = getTranslationID(
        "cardLicenseActivatePopupPage.message.LicenseKeyAlreadyActivatedError"
      );
    }

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

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