import { ConfigurationParameters } from "api";
import { decodeToken } from "../../common/decodeToken";
import { ADMIN_ROLES, USER_ROLES } from "../../components/auth/constants";

/**
 * Get access token
 * @returns access token
 */
export const loadAccessToken = (): string | null =>
  localStorage.getItem("accessToken");
/**
 * Set access token
 * @param accessToken
 */
export const saveAccessToken = (accessToken: string): void => {
  localStorage.setItem("accessToken", accessToken);
};
/**
 * Remove access token
 */
export const removeAccessToken = (): void => {
  localStorage.removeItem("accessToken");
};

/**
 * Get refresh token
 * @returns refresh token
 */
export const loadRefreshToken = (): string | null =>
  localStorage.getItem("refreshToken");
/**
 * Set refresh token
 * @param refreshToken
 */
export const saveRefreshToken = (refreshToken: string): void => {
  localStorage.setItem("refreshToken", refreshToken);
};
/**
 * Remove refresh token
 */
export const removeRefreshToken = (): void => {
  localStorage.removeItem("refreshToken");
};

// 初期状態のAPI Config
export const initialConfig = (): ConfigurationParameters => {
  const config: ConfigurationParameters = {};
  if (import.meta.env.VITE_STAGE === "local") {
    config.basePath = "http://localhost:8081";
  } else {
    config.basePath = `${window.location.origin}/dictation/api`;
  }

  return config;
};

/**
 * is admin user ログインしているユーザがadmin権限を持つかどうかを返す
 * @returns bool
 */
export const isAdminUser = (): boolean => {
  const jwt = loadAccessToken();
  const token = jwt ? decodeToken(jwt) : null;
  if (!token) {
    return false;
  }
  return token.role.includes(ADMIN_ROLES.ADMIN);
};

/**
 * is standard user ログインしているユーザがstandard権限を持つかどうかを返す
 * @returns bool
 */
// TODO 上記の関数とまとめて汎用的な関数にリファクタリングする
export const isStandardUser = (): boolean => {
  const jwt = loadAccessToken();
  const token = jwt ? decodeToken(jwt) : null;
  if (!token) {
    return false;
  }
  return token.role.includes(ADMIN_ROLES.STANDARD);
};

/**
 * is author user ログインしているユーザがAuthorかどうかを返す
 * @returns bool
 */
export const isAuthorUser = (): boolean => {
  const jwt = loadAccessToken();
  const token = jwt ? decodeToken(jwt) : null;
  if (!token) {
    return false;
  }
  return token.role.includes(USER_ROLES.AUTHOR);
};

/**
 * is approve tier ログインしているアカウントの階層を確認したのち返す
 * @returns bool
 */
export const isApproveTier = (tiers: string[]): boolean => {
  const jwt = loadAccessToken();
  const token = jwt && decodeToken(jwt);

  return !!token && tiers.includes(token.tier.toString());
};

/**
 * is typist user ログインしているユーザがTypistかどうかを返す
 * @returns bool
 */
export const isTypistUser = (): boolean => {
  const jwt = loadAccessToken();
  const token = jwt ? decodeToken(jwt) : null;
  if (!token) {
    return false;
  }
  return token.role.includes(USER_ROLES.TYPIST);
};
