import { expect, test } from '@playwright/test';

const shouldRun = process.env.E2E_PADDLE_SANDBOX === '1';

test.describe('Paddle sandbox checkout (staging)', () => {
  test.skip(!shouldRun, 'Set E2E_PADDLE_SANDBOX=1 to run live sandbox checkout on staging.');

  test('creates Paddle checkout session from packages page', async ({ page }) => {
    const base = process.env.E2E_BASE_URL ?? 'https://test-y0k0.fotospiel.app';

    await page.goto(`${base}/packages`);

    const acceptCookies = page.getByRole('button', { name: /akzeptieren|accept/i });
    if (await acceptCookies.isVisible()) {
      await acceptCookies.click();
    }

    const checkoutButtons = page.locator('a:has-text("Paket") , a:has-text("Checkout"), a:has-text("Jetzt"), button:has-text("Checkout")');
    const count = await checkoutButtons.count();

    if (count === 0) {
      test.skip('No checkout CTA found on packages page');
    }

    const [requestPromise] = await Promise.all([
      page.waitForRequest('**/paddle/create-checkout'),
      checkoutButtons.first().click(),
    ]);

    const checkoutRequest = await requestPromise.response();
    expect(checkoutRequest, 'Expected paddle/create-checkout request to resolve').toBeTruthy();
    expect(checkoutRequest!.status()).toBeLessThan(400);

    const body = await checkoutRequest!.json();
    const checkoutUrl = body.checkout_url ?? body.url ?? '';
    expect(checkoutUrl).toContain('paddle');
  });
});
