import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter } from '@angular/router';
import { Members } from './members';
import { TeamStore } from '../../../core/team/team-store';
import { AuthStore } from '../../../core/auth/auth-store';
import { environment } from '../../../../environments/environment';

describe('Members', () => {
  it('renders members and lets an authorized captain create one', async () => {
    const team = {
      id: 5,
      name: 'Team A',
      alias: 'a',
      balance: 0,
      players: [
        {
          id: 1,
          firstName: 'Alex',
          lastName: 'Muster',
          balance: -12,
          active: true,
          teamRole: { id: 3, name: 'captain' },
          user: { id: 42, email: 'a@b.de', firstName: 'Alex', lastName: 'Muster' },
        },
        {
          id: 2,
          firstName: 'Bea',
          lastName: 'Test',
          balance: 5,
          active: true,
          teamRole: { id: 1, name: 'player' },
        },
      ],
    };
    const refreshTeam = vi.fn();
    await TestBed.configureTestingModule({
      imports: [Members],
      providers: [
        provideHttpClient(),
        provideHttpClientTesting(),
        provideRouter([]),
        {
          provide: TeamStore,
          useValue: { team: signal(team), loading: signal(false), refreshTeam },
        },
      ],
    }).compileComponents();
    TestBed.inject(AuthStore).setSession('token', team.players[0].user!);
    const fixture = TestBed.createComponent(Members);
    fixture.detectChanges();
    expect(fixture.nativeElement.textContent).toContain('Bea Test');
    expect(fixture.nativeElement.textContent).toContain('Mitglieder verwalten');

    fixture.componentInstance['showCreateForm'].set(true);
    fixture.componentInstance['createForm'].setValue({
      firstName: 'Chris',
      lastName: 'Neu',
      teamRole: 1,
    });
    fixture.componentInstance['createPlayer']();
    TestBed.inject(HttpTestingController)
      .expectOne(`${environment.apiUrl}teams/5/players`)
      .flush({ id: 3 });
    expect(refreshTeam).toHaveBeenCalled();
  });
});
