import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { environment } from '../../../environments/environment';
import { CashboxExportApi } from './cashbox-export-api';

describe('CashboxExportApi', () => {
  let api: CashboxExportApi;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [provideHttpClient(), provideHttpClientTesting()],
    });
    api = TestBed.inject(CashboxExportApi);
    httpMock = TestBed.inject(HttpTestingController);
  });

  afterEach(() => httpMock.verify());

  it('downloads the cashbox export as a blob with query params', () => {
    api.exportCashbox(5, '2026-08-01', '2026-08-31', 'csv').subscribe();
    const request = httpMock.expectOne(
      `${environment.apiUrl}cashbox-export/5?from=2026-08-01&to=2026-08-31&format=csv`,
    );
    expect(request.request.method).toBe('GET');
    expect(request.request.responseType).toBe('blob');
    request.flush(new Blob(['csv content']));
  });

  it('loads the subscription', () => {
    api.getSubscription(5).subscribe();
    const request = httpMock.expectOne(`${environment.apiUrl}cashbox-export/5/subscription`);
    expect(request.request.method).toBe('GET');
    request.flush({ recipients: [], interval: 'monthly', active: false, nextRunDate: null });
  });

  it('updates the subscription', () => {
    const update = { recipients: ['a@example.com'], interval: 'monthly' as const, active: true };
    api.updateSubscription(5, update).subscribe();
    const request = httpMock.expectOne(`${environment.apiUrl}cashbox-export/5/subscription`);
    expect(request.request.method).toBe('PUT');
    expect(request.request.body).toEqual(update);
    request.flush({ ...update, nextRunDate: '2026-09-01T00:00:00.000Z' });
  });

  it('triggers the due-subscriptions run now', () => {
    api.triggerRunNow().subscribe();
    const request = httpMock.expectOne(`${environment.apiUrl}cashbox-export/admin/run`);
    expect(request.request.method).toBe('POST');
    request.flush(null);
  });
});
