import { getProductRecurringCreateData } from '@/manager/modules/product/product-factories';
import { test } from '@/manager/modules/product/product-fixtures';
import { applyProductRecurringEditBookingPlansPrices } from '@/manager/modules/product/product-mappers';
import { productRecurringEditBookingPlansPricesHappyTestCases } from '@/manager/modules/product/test-cases/product-recurring-edit-booking-plans-prices-happy-test-cases';
import { verifyBookingPlansTable } from '@/manager/modules/ui/booking-plan/booking-plan-assertions';
import { expect } from '@/shared/utils/matchers';

for (const tc of productRecurringEditBookingPlansPricesHappyTestCases) {
  test(tc.description, async ({ createProductRecurring, productRecurringDetailsPage }) => {
    const product = await createProductRecurring(getProductRecurringCreateData(tc.initialOptions));
    const newProduct = applyProductRecurringEditBookingPlansPrices(product, tc.changes);

    await productRecurringDetailsPage.goto(product.id);

    await test.step('select booking plans to change prices', async () => {
      if (tc.changes.selection.all) {
        await productRecurringDetailsPage.bookingPlanCard.dataTable.rowSelector.selectAll();
      } else {
        await productRecurringDetailsPage.bookingPlanCard.dataTable.rowSelector.select(
          tc.changes.selection.indexes.map((index) => product.bookingPlans.length - (index + 1))
        );
      }
    });

    await test.step('change prices of booking plans', async () => {
      const dialog = await productRecurringDetailsPage.bookingPlanCard.openPriceChangeDialog();
      await dialog.edit(tc.changes.priceChange);
    });

    await test.step('verify booking plans on details page', () =>
      verifyBookingPlansTable(
        productRecurringDetailsPage.bookingPlanCard.dataTable,
        newProduct.bookingPlans,
        newProduct.location.currency,
        'recurringProduct'
      ));
  });
}

test('rejects a price change without all required fields', async ({
  createProductRecurring,
  productRecurringDetailsPage,
}) => {
  const product = await createProductRecurring(getProductRecurringCreateData());

  await productRecurringDetailsPage.goto(product.id);

  const dialog = await test.step('submit price change form without required fields', async () => {
    await productRecurringDetailsPage.bookingPlanCard.dataTable.rowSelector.selectAll();
    const priceChangeDialog = await productRecurringDetailsPage.bookingPlanCard.openPriceChangeDialog();
    await priceChangeDialog.submit();
    return priceChangeDialog;
  });

  await test.step('verify errors on form', async () => {
    await expect(dialog.errors).toHaveCountGreaterThan(0);
  });
});
