import { GraphQLFailureDTO, GRAPHQL_UNAUTHORIZED_KEY } from "core/dto_model";
import Failure from "core/failure";
import {
  BaseFailureHandler,
  FailureCallbackFunction,
  ResponseFailureHandler,
} from "core/handlers/responseFailureHandler";

class UnauthorizedHandler
  extends BaseFailureHandler
  implements ResponseFailureHandler
{
  private cb: FailureCallbackFunction;

  constructor(callback: FailureCallbackFunction, nextHandler?: ResponseFailureHandler) {
    super(nextHandler);
    this.cb = callback;
  }

  handle(reason: Failure): void {
    if (!reason.meta || !reason.meta!.isRequestFailure) {
      return super.handle(reason);
    }
    if (
      reason.status === 401 ||
      (reason.meta.data &&
        Array.isArray(reason.meta.data.erros) &&
        (reason.meta.data as GraphQLFailureDTO).errors.findIndex((error) => {
          return error.code === GRAPHQL_UNAUTHORIZED_KEY;
        }) > -1)
    ) {
      this.cb();
    }
  }
}

export default UnauthorizedHandler;
