import { inject, Injectable } from '@angular/core';
import { GenericService } from '@iqser/common-ui';
import { Observable, of, switchMap } from 'rxjs';
import { EmailNotificationScheduleTypes, INotificationPreferences, Notification } from '@red/domain';
import { catchError } from 'rxjs/operators';
import { NotificationsService } from '@services/notifications.service';

@Injectable()
export class NotificationPreferencesService extends GenericService<INotificationPreferences> {
    protected readonly _defaultModelPath = 'notification-preferences';

    readonly #notificationsService = inject(NotificationsService);

    private get _defaultPreferences(): INotificationPreferences {
        return {
            emailNotificationType: EmailNotificationScheduleTypes.INSTANT,
            emailNotifications: [],
            emailNotificationsEnabled: false,
            inAppNotifications: [],
            inAppNotificationsEnabled: true,
        };
    }

    get(): Observable<INotificationPreferences> {
        return super.get<INotificationPreferences>().pipe(catchError(() => of(this._defaultPreferences)));
    }

    update(notificationPreferences: INotificationPreferences): Observable<Notification[]> {
        return super._post(notificationPreferences).pipe(switchMap(() => this.#notificationsService.loadAll()));
    }
}
