import { Injectable, computed, inject, signal } from '@angular/core';
import { take } from 'rxjs/operators';
import { AdminNotification, AdminNotificationFilters } from '../models/admin-notification.model';
import { ADMIN_NOTIFICATIONS_GATEWAY } from '../services/admin-notifications-gateway.token';

@Injectable({ providedIn: 'root' })
export class AdminNotificationsFacade {
  private readonly gateway = inject(ADMIN_NOTIFICATIONS_GATEWAY);

  readonly filters = signal<AdminNotificationFilters>({ marketplaceId: '', eventType: 'all', unreadOnly: false });
  readonly notifications = signal<AdminNotification[]>([]);
  readonly loading = signal(false);

  readonly unreadCount = computed(() => this.notifications().filter(n => !n.read).length);

  load(): void {
    this.loading.set(true);
    this.gateway.loadNotifications(this.filters()).pipe(take(1)).subscribe(items => {
      this.notifications.set(items);
      this.loading.set(false);
    });
  }

  updateFilters(patch: Partial<AdminNotificationFilters>): void {
    this.filters.update(current => ({ ...current, ...patch }));
    this.load();
  }

  markRead(id: string): void {
    this.gateway.markRead(id).pipe(take(1)).subscribe(() => this.load());
  }

  markAllRead(): void {
    this.gateway.markAllRead().pipe(take(1)).subscribe(() => this.load());
  }
}
