import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ProductStockInfoComponent } from './product-stock-info.component';

describe('ProductStockInfoComponent', () => {
  let component: ProductStockInfoComponent;
  let fixture: ComponentFixture<ProductStockInfoComponent>;

  const setInputs = (inputs: Record<string, unknown>) => {
    Object.entries(inputs).forEach(([key, value]) =>
      fixture.componentRef.setInput(key, value),
    );
  };

  const getStockValue = (which: string) =>
    fixture.nativeElement
      .querySelector(`[data-what="stock-value"][data-which="${which}"]`)
      ?.textContent?.trim();

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [ProductStockInfoComponent],
    }).compileComponents();

    fixture = TestBed.createComponent(ProductStockInfoComponent);
    component = fixture.componentInstance;
  });

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

  it('should display the availableStock input', () => {
    setInputs({ availableStock: 42 });
    fixture.detectChanges();
    expect(getStockValue('current-stock')).toBe('42x');
  });

  it('should display the stockToRemit input', () => {
    setInputs({ stockToRemit: 5 });
    fixture.detectChanges();
    expect(getStockValue('remit-amount')).toBe('5x');
  });

  it('should display the targetStock input', () => {
    setInputs({ targetStock: 10 });
    fixture.detectChanges();
    expect(getStockValue('remaining-stock')).toBe('10x');
  });

  it('should display the zob input', () => {
    setInputs({ zob: 99 });
    fixture.detectChanges();
    expect(getStockValue('zob')).toBe('99x');
  });

  it('should render all labels with correct e2e attributes', () => {
    const labels = [
      { which: 'current-stock', text: 'Aktueller Bestand' },
      { which: 'remit-amount', text: 'Remi Menge' },
      { which: 'remaining-stock', text: 'Übriger Bestand' },
      { which: 'zob', text: 'ZOB' },
    ];
    fixture.detectChanges();
    labels.forEach(({ which, text }) => {
      const label = fixture.nativeElement.querySelector(
        `[data-what="stock-label"][data-which="${which}"]`,
      );
      expect(label?.textContent?.trim()).toBe(text);
    });
  });

  it('should display all values as 0x when all inputs are zero', () => {
    setInputs({
      availableStock: 0,
      stockToRemit: 0,
      targetStock: 0,
      zob: 0,
    });
    fixture.detectChanges();
    ['current-stock', 'remit-amount', 'remaining-stock', 'zob'].forEach(
      (which) => expect(getStockValue(which)).toBe('0x'),
    );
  });

  it('should display correct zob value when only zob is set', () => {
    setInputs({ zob: 123 });
    fixture.detectChanges();
    expect(getStockValue('zob')).toBe('123x');
  });
});
