import { TestBed } from '@angular/core/testing';
import { beforeEach, describe, expect, it } from 'vitest';

import { ProductAttribute } from '../../../../core/services/catalog/catalog.interface';
import { ProductAttributeSelectorComponent } from './product-attribute-selector.component';

describe('ProductAttributeSelectorComponent', () => {
  const sizeAttribute: ProductAttribute = {
    id: 1,
    codigo: 'size',
    nombre: 'Size',
    is_required: true,
    metadata_schema: null,
    type: 'select',
    options: [
      { id: 10, value: 'S', label: 'S', sort_order: 0, metadata: null },
      { id: 20, value: 'M', label: 'M', sort_order: 1, metadata: null },
    ],
  };

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

  it('keeps an unlimited option available when maximum quantity is null', () => {
    const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
    fixture.componentRef.setInput('attributes', [sizeAttribute]);
    fixture.componentRef.setInput('inventoryPolicy', 'unlimited');
    fixture.componentRef.setInput('variants', [
      {
        id: 1,
        stock_tecnico: null,
        values: { size: 'S' },
      },
    ]);
    fixture.detectChanges();

    const buttons = Array.from(
      fixture.nativeElement.querySelectorAll('.attribute-selector__text-option'),
    ) as HTMLButtonElement[];
    expect(buttons[0].disabled).toBe(false);
    expect(buttons[1].disabled).toBe(true);
  });

  it('disables tracked options without available stock', () => {
    const fixture = TestBed.createComponent(ProductAttributeSelectorComponent);
    fixture.componentRef.setInput('attributes', [sizeAttribute]);
    fixture.componentRef.setInput('inventoryPolicy', 'tracked');
    fixture.componentRef.setInput('variants', [
      {
        id: 1,
        stock_tecnico: 0,
        values: { size: 'S' },
      },
      {
        id: 2,
        stock_tecnico: 2,
        values: { size: 'M' },
      },
    ]);
    fixture.detectChanges();

    const buttons = Array.from(
      fixture.nativeElement.querySelectorAll('.attribute-selector__text-option'),
    ) as HTMLButtonElement[];
    expect(buttons[0].disabled).toBe(true);
    expect(buttons[1].disabled).toBe(false);
  });
});
