import { isDevMode, inject, Injectable } from '@angular/core';
import { TuiNotificationService } from '@taiga-ui/core/components/notification';

import { DevLogService } from '../devtools/dev-log.service';
import { classifyUserError } from '../http/error-classification.util';
import { escapeHtml, httpErrorMessage } from '../http/http-error.util';
import { friendlyMessageForUserError } from './user-error-messages.config';

const ERROR_TOAST_TITLE = 'Что-то пошло не так...';

@Injectable({ providedIn: 'root' })
export class UserErrorNotifyService {
  private readonly notifications = inject(TuiNotificationService);
  private readonly devLog = inject(DevLogService);

  notifySuccess(message: string, label: string): void {
    this.notifications
      .open(escapeHtml(message), {
        label,
        appearance: 'positive',
        autoClose: 4000,
        closable: true,
        size: 'm',
      })
      .subscribe();
  }

  notifyError(err: unknown, source: string): void {
    const kind = classifyUserError(err);
    const userSubtitle = friendlyMessageForUserError(kind);
    const technical = httpErrorMessage(err);

    if (isDevMode()) {
      this.devLog.add({
        level: 'error',
        source: 'system',
        message: `${source}: ${technical}`,
      });
    }

    this.notifications
      .open(escapeHtml(userSubtitle), {
        label: ERROR_TOAST_TITLE,
        appearance: 'negative',
        autoClose: 10000,
      })
      .subscribe();
  }
}
