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

export const createCardLicenseAsync = createAsyncThunk<
  IssueCardLicensesResponse,
  {
    // パラメータ
    createCount: number;
  },
  {
    // rejectした時の返却値の型s
    rejectValue: {
      error: ErrorObject;
    };
  }
>("licenses/createCardLicenseAsync", async (args, thunkApi) => {
  const { createCount } = 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 {
    const res = await licensesApi.issueCardLicenses(
      {
        createCount,
      },
      {
        headers: { authorization: `Bearer ${accessToken}` },
      }
    );
    thunkApi.dispatch(
      openSnackbar({
        level: "info",
        message: getTranslationID(
          "cardLicenseIssuePopupPage.message.createSuccess"
        ),
      })
    );
    return res.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 });
  }
});
