import { Injectable, inject, signal } from '@angular/core';
import { take } from 'rxjs/operators';
import { AdminMonitoringEvent, AdminMonitoringEventFilters, AdminQueue, AdminWebhookDelivery } from '../models/admin-monitoring.model';
import { ADMIN_MONITORING_GATEWAY } from '../services/admin-monitoring-gateway.token';

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

  readonly filters = signal<AdminMonitoringEventFilters>({ category: 'all', search: '' });
  readonly events = signal<AdminMonitoringEvent[]>([]);
  readonly queues = signal<AdminQueue[]>([]);
  readonly webhooks = signal<AdminWebhookDelivery[]>([]);
  readonly loading = signal(false);
  readonly error = signal(false);

  loadAll(): void {
    this.loading.set(true);
    this.error.set(false);
    this.gateway.loadEvents(this.filters()).pipe(take(1)).subscribe({
      next: events => { this.events.set(events); this.loading.set(false); },
      error: () => { this.events.set([]); this.loading.set(false); this.error.set(true); }
    });
    this.gateway.loadQueues().pipe(take(1)).subscribe(queues => this.queues.set(queues));
    this.gateway.loadWebhooks().pipe(take(1)).subscribe(webhooks => this.webhooks.set(webhooks));
  }

  updateFilters(patch: Partial<AdminMonitoringEventFilters>): void {
    this.filters.update(current => ({ ...current, ...patch }));
    this.gateway.loadEvents(this.filters()).pipe(take(1)).subscribe(events => this.events.set(events));
  }
}
