import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TransactionsApi } from './transactions-api';
import { environment } from '../../../environments/environment';
import {
  CreatePlayerTransaction,
  CreateTeamWalletTransaction,
} from '../../models/transaction.model';

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

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

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

  it('loads the combined activity feed for a team', () => {
    const activities = [
      {
        id: 1,
        date: '2026-07-31',
        amount: 12,
        type: 'credit',
        note: '',
        playerName: 'Alex',
        isTeamWalletTransaction: false,
      },
    ];
    api.loadTeamTransactions(5).subscribe((response) => expect(response).toEqual(activities));
    const request = httpMock.expectOne(`${environment.apiUrl}teams/5/transactions`);
    expect(request.request.method).toBe('GET');
    request.flush(activities);
  });

  it('creates player transactions as one batch', () => {
    const transactions: CreatePlayerTransaction[] = [
      {
        playerId: 7,
        date: '2026-07-31T10:00:00.000Z',
        amount: 12.5,
        type: 11,
        note: 'Training',
      },
    ];

    api.createPlayerTransactions(transactions).subscribe();

    const request = httpMock.expectOne(`${environment.apiUrl}transactions`);
    expect(request.request.method).toBe('POST');
    expect(request.request.body).toEqual(transactions);
    request.flush([]);
  });

  it('creates a team wallet transaction', () => {
    const transaction: CreateTeamWalletTransaction = {
      teamId: 5,
      date: '2026-07-31T10:00:00.000Z',
      amount: 35,
      type: 14,
      note: 'Material',
    };

    api.createTeamWalletTransaction(transaction).subscribe();

    const request = httpMock.expectOne(`${environment.apiUrl}team-wallet-transactions`);
    expect(request.request.method).toBe('POST');
    expect(request.request.body).toEqual(transaction);
    request.flush({ id: 3 });
  });

  it('reverses a player transaction', () => {
    api.reverseTransaction(42).subscribe();

    const request = httpMock.expectOne(`${environment.apiUrl}transactions/42/reverse`);
    expect(request.request.method).toBe('POST');
    expect(request.request.body).toEqual({});
    request.flush({ id: 43 });
  });
});
