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 { RecurringTransactionApi } from './recurring-transaction-api';

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

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

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

  it('loads the recurring transactions of a team', () => {
    api.loadRecurringTransactions(5).subscribe();
    const request = httpMock.expectOne(`${environment.apiUrl}recurring-transactions/5`);
    expect(request.request.method).toBe('GET');
    request.flush([]);
  });

  it('creates a recurring transaction', () => {
    const entry = {
      teamId: 5,
      description: 'Monatsbeitrag',
      amount: 10,
      type: 13,
      interval: 'monthly' as const,
      startDate: '2026-09-01T00:00:00.000Z',
    };
    api.createRecurringTransaction(entry).subscribe();
    const request = httpMock.expectOne(`${environment.apiUrl}recurring-transactions`);
    expect(request.request.method).toBe('POST');
    expect(request.request.body).toEqual(entry);
    request.flush({ id: 1, ...entry });
  });

  it('updates a recurring transaction', () => {
    const update = {
      description: 'Monatsbeitrag',
      amount: 12,
      type: 12,
      interval: 'quarterly' as const,
      active: false,
    };
    api.updateRecurringTransaction(8, update).subscribe();
    const request = httpMock.expectOne(`${environment.apiUrl}recurring-transactions/8`);
    expect(request.request.method).toBe('PATCH');
    expect(request.request.body).toEqual(update);
    request.flush({ id: 8, ...update });
  });

  it('deletes a recurring transaction', () => {
    api.deleteRecurringTransaction(8).subscribe();
    const request = httpMock.expectOne(`${environment.apiUrl}recurring-transactions/8`);
    expect(request.request.method).toBe('DELETE');
    request.flush(null);
  });
});
