import { test, expectFixture as expect } from '../helpers/test-fixtures';

const shouldRun = process.env.E2E_TESTING_API === '1';
const demoTenantCredentials = {
  email: process.env.E2E_DEMO_TENANT_EMAIL ?? 'tenant-demo@fotospiel.app',
  password: process.env.E2E_DEMO_TENANT_PASSWORD ?? 'Demo1234!',
};

test.describe('Standard package checkout with coupons', () => {
  test.skip(!shouldRun, 'Set E2E_TESTING_API=1 to enable checkout tests that use /api/_testing endpoints.');
  test('applies seeded coupon and shows discount summary', async ({
    page,
    seedTestCoupons,
  }) => {
    await seedTestCoupons();

    await page.goto('/de/packages');

    const detailsButtons = page.getByRole('button', {
      name: /Details ansehen|Details anzeigen|View details/i,
    });
    await expect(detailsButtons.first()).toBeVisible();

    await detailsButtons.nth(1).click();

    const dialog = page.getByRole('dialog');
    await expect(dialog).toBeVisible();
    await expect(dialog.getByRole('heading', { name: /Standard/i })).toBeVisible();

    await dialog.getByRole('link', { name: /Jetzt bestellen|Order now|Jetzt buchen/i }).click();

    await expect(page).toHaveURL(/\/(bestellen|checkout)\/\d+/);

    await page.getByRole('button', { name: /^Weiter$/ }).first().click();

    await page.getByRole('button', { name: /^Anmelden$/ }).first().click();

    await expect(page.locator('input[name="identifier"]')).toBeVisible();
    await page.fill('input[name="identifier"]', demoTenantCredentials.email);
    await page.fill('input[name="password"]', demoTenantCredentials.password);
    await page.getByRole('button', { name: /^Anmelden$/ }).last().click();

    await expect(page.getByPlaceholder(/Gutscheincode/i)).toBeVisible();

    await page.getByPlaceholder(/Gutscheincode/i).fill('PERCENT10');
    await page.getByRole('button', { name: /Gutschein anwenden|Apply coupon/i }).click();

    await expect(page.getByText(/Gutschein PERCENT10 aktiviert/i)).toBeVisible();
    await expect(page.getByText(/Rabatt|Discount/i)).toBeVisible();
    await expect(page.getByText(/Gesamtsumme|Total|Gesamt/i)).toBeVisible();
  });
});
