import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { MatDialogRef } from '@angular/material/dialog';
import { CreateTeamDialog } from './create-team-dialog';
import { environment } from '../../../../environments/environment';

describe('CreateTeamDialog', () => {
  let dialogRef: { close: ReturnType<typeof vi.fn> };
  let httpMock: HttpTestingController;

  beforeEach(async () => {
    dialogRef = { close: vi.fn() };
    await TestBed.configureTestingModule({
      imports: [CreateTeamDialog],
      providers: [
        provideHttpClient(),
        provideHttpClientTesting(),
        { provide: MatDialogRef, useValue: dialogRef },
      ],
    }).compileComponents();
    httpMock = TestBed.inject(HttpTestingController);
  });

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

  it('keeps the submit button disabled until a team name is entered', () => {
    const fixture = TestBed.createComponent(CreateTeamDialog);
    fixture.detectChanges();

    expect(fixture.componentInstance['form'].invalid).toBe(true);

    fixture.componentInstance['form'].controls.name.setValue('1. Herren');
    expect(fixture.componentInstance['form'].invalid).toBe(false);
  });

  it('creates the team and closes the dialog with the created team', () => {
    const fixture = TestBed.createComponent(CreateTeamDialog);
    fixture.detectChanges();

    fixture.componentInstance['form'].controls.name.setValue('1. Herren');
    fixture.componentInstance['submit']();

    const request = httpMock.expectOne(`${environment.apiUrl}teams`);
    expect(request.request.body).toEqual({ name: '1. Herren' });
    request.flush({ id: 9, name: '1. Herren', alias: 'a', balance: 0 });

    expect(dialogRef.close).toHaveBeenCalledWith({
      id: 9,
      name: '1. Herren',
      alias: 'a',
      balance: 0,
    });
  });

  it('re-enables the form and keeps the dialog open when the request fails', () => {
    const fixture = TestBed.createComponent(CreateTeamDialog);
    fixture.detectChanges();

    fixture.componentInstance['form'].controls.name.setValue('1. Herren');
    fixture.componentInstance['submit']();

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

    expect(dialogRef.close).not.toHaveBeenCalled();
    expect(fixture.componentInstance['saving']()).toBe(false);
  });
});
