import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { throwError } from 'rxjs';
import { provideRouter } from '@angular/router';
import { MatSnackBar } from '@angular/material/snack-bar';
import { AuthApi } from '../../../../core/auth/auth-api';
import { AuthStore } from '../../../../core/auth/auth-store';
import { HelpAccessService } from '../../../../core/help/help-access';
import { Profile } from './profile';

describe('Profile', () => {
  it('updates profile names and refreshes the auth store', async () => {
    const updated = {
      id: 42,
      email: 'alex@example.com',
      firstName: 'Alexander',
      lastName: 'Neu',
      helpTextsEnabled: false,
    };
    const updateProfile = vi.fn(() => of(updated));
    const updateUser = vi.fn();
    await TestBed.configureTestingModule({
      imports: [Profile],
      providers: [
        provideRouter([]),
        { provide: AuthApi, useValue: { updateProfile } },
        {
          provide: AuthStore,
          useValue: {
            currentUser: signal({
              id: 42,
              email: 'alex@example.com',
              firstName: 'Alex',
              lastName: 'Muster',
              helpTextsEnabled: true,
            }),
            updateUser,
          },
        },
        { provide: HelpAccessService, useValue: { canOpenGuide: signal(true) } },
      ],
    }).compileComponents();
    const fixture = TestBed.createComponent(Profile);
    fixture.detectChanges();
    fixture.componentInstance['form'].setValue({
      firstName: 'Alexander',
      lastName: 'Neu',
      oldPassword: '',
      password: '',
      helpTextsEnabled: false,
    } as any);

    fixture.componentInstance['save']();

    expect(updateProfile).toHaveBeenCalledWith({
      firstName: 'Alexander',
      lastName: 'Neu',
      helpTextsEnabled: false,
    });
    expect(updateUser).toHaveBeenCalledWith(updated);
  });

  it('keeps the stored preference and reports an error when saving fails', async () => {
    const updateUser = vi.fn();
    await TestBed.configureTestingModule({
      imports: [Profile],
      providers: [
        provideRouter([]),
        {
          provide: AuthApi,
          useValue: { updateProfile: vi.fn(() => throwError(() => new Error('failed'))) },
        },
        {
          provide: AuthStore,
          useValue: {
            currentUser: signal({
              id: 42,
              email: 'alex@example.com',
              firstName: 'Alex',
              lastName: 'Muster',
              helpTextsEnabled: true,
            }),
            updateUser,
          },
        },
        { provide: HelpAccessService, useValue: { canOpenGuide: signal(true) } },
      ],
    }).compileComponents();
    const fixture = TestBed.createComponent(Profile);
    const snackBar = fixture.debugElement.injector.get(MatSnackBar);
    const open = vi.spyOn(snackBar, 'open');
    fixture.detectChanges();
    fixture.componentInstance['form'].patchValue({ helpTextsEnabled: false } as any);

    fixture.componentInstance['save']();

    expect(updateUser).not.toHaveBeenCalled();
    expect(open).toHaveBeenCalledWith('Profil konnte nicht gespeichert werden.', undefined, {
      duration: 5000,
    });
  });
});
