import { InvoiceIssueCreditNoteItem } from '@/manager/modules/invoice/invoice-types';
import { Checkbox } from '@/manager/shared/components/Checkbox';
import { NumberField } from '@/manager/shared/components/NumberField';
import { SingleAutocomplete } from '@/manager/shared/components/SingleAutocomplete';
import { BaseComponent } from '@/shared/base/BaseComponent';

export class InvoiceIssueCreditNoteItemList extends BaseComponent {
  readonly rows = this.host.getByTestId('credit-note-line-item');

  // TODO: every item must have a unique name
  async select(items: InvoiceIssueCreditNoteItem[]): Promise<void> {
    for (const item of items) {
      const host = this.rows.filter({ hasText: item.name });
      const toCreditCheckbox = new Checkbox(host.getByTestId('column-description'));
      const creditQuantityAutocomplete = new SingleAutocomplete(host.getByTestId('column-credit-quantity'));
      const creditAmountNumberField = new NumberField(host.getByTestId('column-credit-amount'));

      if (!item.selected) {
        await toCreditCheckbox.set(item.selected);
        continue;
      }

      if (item.creditQuantity && item.quantity > item.creditQuantity) {
        await creditQuantityAutocomplete.fill(item.creditQuantity.toString());
        continue;
      }

      if (!item.creditQuantity && item.creditAmount && item.priceExclVat * item.quantity > item.creditAmount) {
        await creditAmountNumberField.fill(item.creditAmount);
        continue;
      }
    }
  }
}
