import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { MyTeamsStore } from './my-teams-store';
import { environment } from '../../../environments/environment';
import { Player } from '../../models/player.model';

describe('MyTeamsStore', () => {
  let store: MyTeamsStore;
  let httpMock: HttpTestingController;

  const player: Player = {
    id: 1,
    firstName: 'A',
    lastName: 'B',
    balance: 0,
    active: true,
    team: { id: 5, name: 'Team A', alias: 'team-a', balance: 0 },
  };

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

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

  it('loads and exposes the players for a user', () => {
    store.ensureLoaded(42);
    expect(store.loading()).toBe(true);

    const request = httpMock.expectOne(`${environment.apiUrl}users/42/teams`);
    request.flush([player]);

    expect(store.loading()).toBe(false);
    expect(store.players()).toEqual([player]);
  });

  it('does not reload for the same user id', () => {
    store.ensureLoaded(42);
    httpMock.expectOne(`${environment.apiUrl}users/42/teams`).flush([player]);

    store.ensureLoaded(42);

    httpMock.expectNone(`${environment.apiUrl}users/42/teams`);
  });

  it('resets loading on error without throwing', () => {
    store.ensureLoaded(42);

    httpMock.expectOne(`${environment.apiUrl}users/42/teams`).flush('error', {
      status: 500,
      statusText: 'Server Error',
    });

    expect(store.loading()).toBe(false);
    expect(store.players()).toEqual([]);
  });
});
