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

export const listUsersAsync = createAsyncThunk<
  // 正常時の戻り値の型
  GetUsersResponse,
  // 引数
  void,
  {
    // rejectした時の返却値の型
    rejectValue: {
      error: ErrorObject;
    };
  }
>("users/listUsersAsync", async (args, thunkApi) => {
  // apiのConfigurationを取得する
  const { getState } = thunkApi;
  const state = getState() as RootState;
  const { configuration, accessToken } = state.auth;
  const config = new Configuration(configuration);
  const usersApi = new UsersApi(config);

  try {
    const res = await usersApi.getUsers({
      headers: { authorization: `Bearer ${accessToken}` },
    });

    return { users: res.data.users };
  } catch (e) {
    // e ⇒ errorObjectに変換
    const error = createErrorObject(e);

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

export const addUserAsync = createAsyncThunk<
  {
    /* Empty Object */
  },
  SignupRequest,
  {
    // rejectした時の返却値の型
    rejectValue: {
      error: ErrorObject;
    };
  }
>("users/addUserAsync", async (args, thunkApi) => {
  const {
    name,
    email,
    role,
    authorId,
    typistGroupId,
    autoRenew,
    licenseAlert,
    notification,
  } = args;

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

  try {
    await usersApi.signup(
      {
        name,
        email,
        role,
        authorId,
        typistGroupId,
        autoRenew,
        licenseAlert,
        notification,
      },
      {
        headers: { authorization: `Bearer ${accessToken}` },
      }
    );
    thunkApi.dispatch(
      openSnackbar({
        level: "info",
        message: getTranslationID("userListPage.message.addUserSuccess"),
      })
    );
    return {};
  } catch (e) {
    // e ⇒ errorObjectに変換"z
    const error = createErrorObject(e);

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

    if (error.code === "E010301") {
      errorMessage = getTranslationID(
        "signupConfirmPage.message.emailConflictError"
      );
    }
    if (error.code === "E010302") {
      errorMessage = getTranslationID(
        "userListPage.message.authorIdConflictError"
      );
    }

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

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