import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideRouter, Router } from '@angular/router';
import { Login } from './login';
import { environment } from '../../../../environments/environment';
import { AuthStore } from '../../../core/auth/auth-store';

describe('Login', () => {
  let httpMock: HttpTestingController;
  let router: Router;
  let authStore: AuthStore;

  beforeEach(async () => {
    localStorage.clear();
    await TestBed.configureTestingModule({
      imports: [Login],
      providers: [provideHttpClient(), provideHttpClientTesting(), provideRouter([])],
    }).compileComponents();

    httpMock = TestBed.inject(HttpTestingController);
    router = TestBed.inject(Router);
    authStore = TestBed.inject(AuthStore);
  });

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

  it('logs in and navigates to team-select on success', () => {
    const fixture = TestBed.createComponent(Login);
    const navigateSpy = vi.spyOn(router, 'navigate');
    fixture.componentInstance['form'].setValue({ email: 'a@b.de', password: 'secret' });
    fixture.componentInstance['onSubmit']();

    const user = { id: 1, email: 'a@b.de', firstName: 'A', lastName: 'B' };
    httpMock.expectOne(`${environment.apiUrl}auth/email/login`).flush({ token: 'jwt-token', user });

    expect(authStore.isLoggedIn()).toBe(true);
    expect(navigateSpy).toHaveBeenCalledWith(['/team-select']);
  });

  it('shows an error message when login fails', () => {
    const fixture = TestBed.createComponent(Login);
    fixture.componentInstance['form'].setValue({ email: 'a@b.de', password: 'wrong' });
    fixture.componentInstance['onSubmit']();

    httpMock
      .expectOne(`${environment.apiUrl}auth/email/login`)
      .flush('unauthorized', { status: 401, statusText: 'Unauthorized' });

    expect(fixture.componentInstance['errorMessage']()).toBe(
      'Anmeldung fehlgeschlagen. Bitte E-Mail und Passwort prüfen.',
    );
  });
});
