import { TestBed } from '@angular/core/testing';
import { of, throwError } from 'rxjs';
import { AdminMonitoringFacade } from './admin-monitoring.facade';
import { ADMIN_MONITORING_GATEWAY } from '../services/admin-monitoring-gateway.token';
import { AdminMonitoringGateway } from '../services/admin-monitoring-gateway.interface';

describe('AdminMonitoringFacade', () => {
  let facade: AdminMonitoringFacade;
  let gateway: jasmine.SpyObj<AdminMonitoringGateway>;

  beforeEach(() => {
    gateway = jasmine.createSpyObj<AdminMonitoringGateway>('AdminMonitoringGateway', [
      'loadEvents', 'loadQueues', 'loadWebhooks',
    ]);
    TestBed.configureTestingModule({ providers: [{ provide: ADMIN_MONITORING_GATEWAY, useValue: gateway }] });
    facade = TestBed.inject(AdminMonitoringFacade);
  });

  it('loadAll populates events, queues, and webhooks independently', () => {
    gateway.loadEvents.and.returnValue(of([{ id: 'e1' } as any]));
    gateway.loadQueues.and.returnValue(of([{ id: 'q1' } as any]));
    gateway.loadWebhooks.and.returnValue(of([{ id: 'w1' } as any]));

    facade.loadAll();

    expect(facade.events().length).toBe(1);
    expect(facade.queues().length).toBe(1);
    expect(facade.webhooks().length).toBe(1);
  });

  it('an events failure clears events and sets error, without blocking queues/webhooks from loading', () => {
    gateway.loadEvents.and.returnValue(throwError(() => new Error('x')));
    gateway.loadQueues.and.returnValue(of([{ id: 'q1' } as any]));
    gateway.loadWebhooks.and.returnValue(of([]));

    facade.loadAll();

    expect(facade.events()).toEqual([]);
    expect(facade.error()).toBeTrue();
    expect(facade.queues().length).toBe(1);
  });

  it('updateFilters merges the patch and refetches events using the merged filters', () => {
    gateway.loadEvents.and.returnValue(of([]));
    gateway.loadQueues.and.returnValue(of([]));
    gateway.loadWebhooks.and.returnValue(of([]));
    facade.loadAll();

    facade.updateFilters({ search: 'checkout' });

    expect(facade.filters()).toEqual({ category: 'all', search: 'checkout' });
    expect(gateway.loadEvents).toHaveBeenCalledWith({ category: 'all', search: 'checkout' });
  });
});
