import { createComponentFactory, Spectator } from '@ngneat/spectator/jest';
import { MessageDialogComponent, MessageDialogData } from './message-dialog.component';
import { DialogRef, DIALOG_DATA } from '@angular/cdk/dialog';
import { ButtonComponent } from '@isa/ui/buttons';
import { DialogComponent } from '../dialog.component';

// Test suite for default behavior
describe('MessageDialogComponent', () => {
  let spectator: Spectator<MessageDialogComponent>;
  let mockDialogRef: DialogRef<void>;
  const mockData: MessageDialogData = {
    message: 'Test message'
  };

  const createComponent = createComponentFactory({
    component: MessageDialogComponent,
    imports: [ButtonComponent],
    providers: [
      { 
        provide: DialogRef,
        useValue: { close: jest.fn() }
      },
      { 
        provide: DIALOG_DATA,
        useValue: mockData
      },
      {
        provide: DialogComponent,
        useValue: {}
      }
    ],
  });

  beforeEach(() => {
    spectator = createComponent();
    mockDialogRef = spectator.inject(DialogRef);
    jest.clearAllMocks();
  });

  it('should create', () => {
    expect(spectator.component).toBeTruthy();
  });

  it('should display the message passed in data', () => {
    const messageElement = spectator.query('[data-what="message"]');
    expect(messageElement).toHaveText('Test message');
  });

  it('should use default "Schließen" text when closeText is not provided', () => {
    const closeButton = spectator.query('[data-what="button"][data-which="close"]');
    expect(closeButton).toHaveText('Schließen');
  });

  it('should close the dialog when close button is clicked', () => {
    // First verify button exists before clicking
    const closeButtonExists = spectator.query('[data-what="button"][data-which="close"]');
    expect(closeButtonExists).toBeTruthy();
    
    // Act - use selector string directly since we verified it exists
    spectator.click('[data-what="button"][data-which="close"]');
    
    // Assert
    expect(mockDialogRef.close).toHaveBeenCalledTimes(1);
  });
});

// Rather than try to change providers for an existing test instance,
// create a completely separate test for the custom text scenario
describe('MessageDialogComponent with custom text', () => {
  const customCloseText = 'Custom Close Text';
  const customData: MessageDialogData = { 
    message: 'Test message', 
    closeText: customCloseText 
  };

  const createComponent = createComponentFactory({
    component: MessageDialogComponent,
    imports: [ButtonComponent],
    providers: [
      { provide: DialogRef, useValue: { close: jest.fn() } },
      { provide: DIALOG_DATA, useValue: customData },
      { provide: DialogComponent, useValue: {} }
    ],
  });

  it('should use custom close text when provided', () => {
    const spectator = createComponent();
    const closeButton = spectator.query('[data-what="button"][data-which="close"]');
    expect(closeButton).toHaveText(customCloseText);
  });
});
