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

export const orderLicenseAsync = createAsyncThunk<
  {
    /* Empty Object */
  },
  {
    // パラメータ
    poNumber: string;
    orderCount: number;
  },
  {
    // rejectした時の返却値の型
    rejectValue: {
      error: ErrorObject;
    };
  }
>("licenses/orderLicenseAsync", async (args, thunkApi) => {
  const { poNumber, orderCount } = 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.createOrders(
      {
        poNumber,
        orderCount,
      },
      {
        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 === "E010401") {
      errorMessage = getTranslationID(
        "licenseOrderPage.message.poNumberConflictError"
      );
    }

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

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