import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { ActivatedRoute, convertToParamMap, provideRouter, Router } from '@angular/router';
import { Register } from './register';
import { environment } from '../../../../environments/environment';

describe('Register', () => {
  let httpMock: HttpTestingController;
  let router: Router;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [Register],
      providers: [
        provideHttpClient(),
        provideHttpClientTesting(),
        provideRouter([]),
        {
          provide: ActivatedRoute,
          useValue: { snapshot: { queryParamMap: convertToParamMap({ token: 'invite-token' }) } },
        },
      ],
    }).compileComponents();
    httpMock = TestBed.inject(HttpTestingController);
    router = TestBed.inject(Router);
  });

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

  it('verifies the invitation and links its player during registration', () => {
    const fixture = TestBed.createComponent(Register);
    const navigateSpy = vi.spyOn(router, 'navigate');
    fixture.detectChanges();

    httpMock.expectOne(`${environment.apiUrl}auth/verify-invite`).flush({
      teamId: 5,
      teamName: 'Team A',
      playerId: 7,
      playerName: 'Alex Muster',
    });

    fixture.componentInstance['form'].setValue({
      email: 'alex@example.de',
      firstName: 'Alex',
      lastName: 'Muster',
      password: 'secret1',
      passwordConfirmation: 'secret1',
    });
    fixture.componentInstance['onSubmit']();

    const request = httpMock.expectOne(`${environment.apiUrl}auth/email/register`);
    expect(request.request.body.linkPlayerId).toBe(7);
    request.flush(null);

    expect(navigateSpy).toHaveBeenCalledWith(['/auth/login'], { replaceUrl: true });
  });
});
