import { HttpErrorResponse } from '@angular/common/http';
import { TimeoutError } from 'rxjs';

import type { UserErrorKind } from '../notifications/user-error-messages.config';

function isParseFailureMessage(message: string | undefined): boolean {
  return !!message?.includes('Http failure during parsing');
}

export function classifyUserError(err: unknown): UserErrorKind {
  if (err instanceof TimeoutError) {
    return 'timeout';
  }

  if (err instanceof HttpErrorResponse) {
    if (isParseFailureMessage(err.message)) {
      return 'parse_error';
    }
    const s = err.status;
    if (s === 0) {
      return 'network';
    }
    if (s === 408) {
      return 'timeout';
    }
    if (s === 401) {
      return 'unauthorized';
    }
    if (s === 403) {
      return 'forbidden';
    }
    if (s === 404) {
      return 'not_found';
    }
    if (s === 400) {
      return 'bad_request';
    }
    if (s >= 500) {
      return 'server_error';
    }
    if (s >= 400 && s < 500) {
      return 'client_error';
    }
    return 'unknown';
  }

  if (err instanceof Error) {
    const m = err.message;
    if (isParseFailureMessage(m)) {
      return 'parse_error';
    }
    if (/идентификатор|некорректн/i.test(m)) {
      return 'invalid_input';
    }
    if (/timeout|timed out/i.test(m)) {
      return 'timeout';
    }
    if (/network|failed to fetch|load failed|net::/i.test(m)) {
      return 'network';
    }
  }

  return 'unknown';
}
