import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { signal } from '@angular/core';
import { AdminSettingsPageComponent } from './admin-settings-page.component';
import { AdminOrderWatcherService } from '../../shell/services/admin-order-watcher.service';

describe('AdminSettingsPageComponent notification interval', () => {
  let watcherStub: {
    intervalMs: ReturnType<typeof signal<number>>;
    setIntervalSeconds: jasmine.Spy;
  };

  beforeEach(() => {
    watcherStub = {
      intervalMs: signal(15000),
      setIntervalSeconds: jasmine.createSpy('setIntervalSeconds').and.returnValue(true),
    };

    TestBed.configureTestingModule({
      imports: [AdminSettingsPageComponent],
      providers: [
        provideRouter([]),
        { provide: AdminOrderWatcherService, useValue: watcherStub },
      ],
    });
  });

  it('initializes the draft from the current interval in seconds', () => {
    const fixture = TestBed.createComponent(AdminSettingsPageComponent);
    expect(fixture.componentInstance.notificationIntervalSecondsDraft()).toBe(15);
  });

  it('saveNotificationInterval calls setIntervalSeconds with the draft value', () => {
    const fixture = TestBed.createComponent(AdminSettingsPageComponent);
    const component = fixture.componentInstance;

    component.notificationIntervalSecondsDraft.set(30);
    component.saveNotificationInterval();

    expect(watcherStub.setIntervalSeconds).toHaveBeenCalledWith(30);
  });

  it('shows the saved message and keeps the draft when the interval is applied', () => {
    watcherStub.setIntervalSeconds.and.callFake((seconds: number) => {
      watcherStub.intervalMs.set(seconds * 1000);
      return true;
    });
    const fixture = TestBed.createComponent(AdminSettingsPageComponent);
    const component = fixture.componentInstance;

    component.notificationIntervalSecondsDraft.set(30);
    component.saveNotificationInterval();

    expect(component.showNotificationIntervalSaved()).toBe(true);
    expect(component.notificationIntervalSecondsDraft()).toBe(30);
  });

  it('does not show the saved message and reverts the draft when the interval is rejected', () => {
    watcherStub.setIntervalSeconds.and.returnValue(false);
    const fixture = TestBed.createComponent(AdminSettingsPageComponent);
    const component = fixture.componentInstance;

    component.notificationIntervalSecondsDraft.set(0);
    component.saveNotificationInterval();

    expect(component.showNotificationIntervalSaved()).toBe(false);
    expect(component.notificationIntervalSecondsDraft()).toBe(15);
  });
});
