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

test.describe('Standard package checkout with Paddle completion', () => {
  test('registers, applies coupon, and reaches confirmation', async ({
    page,
    clearTestMailbox,
    getLatestCheckoutSession,
    simulatePaddleCompletion,
    getTestMailbox,
  }) => {
    await clearTestMailbox();

    const unique = Date.now();
    const email = `checkout+${unique}@example.test`;
    const password = 'Password123!';
    const username = `playwright-${unique}`;

    await page.addInitScript(() => {
      window.__openedWindows = [];
      const originalOpen = window.open;
      window.open = function (...args) {
        window.__openedWindows.push(args);
        return originalOpen?.apply(this, args) ?? null;
      };
    });

    await page.route('https://cdn.paddle.com/paddle/v2/paddle.js', async (route) => {
      await route.fulfill({
        status: 200,
        contentType: 'application/javascript',
        body: `
          window.__paddleEventCallback = null;
          window.__paddleInitOptions = null;
          window.__paddleCheckoutConfig = null;
          window.Paddle = {
            Environment: { set() {} },
            Initialize(options) {
              window.__paddleInitOptions = options;
              window.__paddleEventCallback = options?.eventCallback || null;
            },
            Checkout: {
              open(config) {
                window.__paddleCheckoutConfig = config;
              },
            },
          };
        `,
      });
    });

    let paddleRequestPayload: Record<string, unknown> | null = null;
    await page.route('**/paddle/create-checkout', async (route) => {
      paddleRequestPayload = route.request().postDataJSON() as Record<string, unknown>;
      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({
          checkout_url: 'https://sandbox.paddle.test/checkout/abc123',
        }),
      });
    });

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

    const standardDetailsButton = page
      .getByRole('heading', { name: /^Standard$/ })
      .locator('..')
      .getByRole('button', { name: /Details/i })
      .first();

    await expect(standardDetailsButton).toBeVisible();
    await standardDetailsButton.click();

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

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

    await expect(page.getByRole('heading', { name: 'Registrieren' })).toBeVisible();

    await page.getByLabel(/Vorname/i).fill('Playwright');
    await page.getByLabel(/Nachname/i).fill('Tester');
    await page.getByLabel(/E-Mail/i).fill(email);
    await page.getByLabel(/Telefon/i).fill('+49123456789');
    await page.getByLabel(/Adresse/i).fill('Teststr. 1, 12345 Berlin');
    await page.getByLabel(/Username/i).fill(username);
    await page.getByLabel(/^Passwort$/i).fill(password);
    await page.getByLabel(/Passwort bestätigen/i).fill(password);
    await page.getByLabel(/Datenschutzerklärung/i).check();
    await page.getByRole('button', { name: /^Registrieren$/ }).click();

    await expect(page.getByRole('heading', { name: 'Zahlung' })).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/i)).toBeVisible();

    await page.getByRole('button', { name: /Weiter mit Paddle|Continue with Paddle/i }).click();

    await expect.poll(async () => page.evaluate(() => window.__paddleCheckoutConfig)).not.toBeNull();
    await expect.poll(async () => {
      return page.evaluate(() => window.__openedWindows?.length ?? 0);
    }).toBe(1);
    await expect.poll(async () => {
      return page.evaluate(() => window.__openedWindows?.[0]?.[0] ?? null);
    }).toContain('https://sandbox.paddle.test/checkout/abc123');

    await page.evaluate(() => {
      window.__paddleEventCallback?.({ name: 'checkout.completed' });
    });

    let session = null;
    for (let i = 0; i < 6; i++) {
      session = await getLatestCheckoutSession({ email });
      if (session) {
        break;
      }
      await page.waitForTimeout(500);
    }

    expect(session).not.toBeNull();
    await simulatePaddleCompletion(session!.id);

    for (let i = 0; i < 6; i++) {
      const refreshed = await getLatestCheckoutSession({ email });
      if (refreshed?.status === 'completed') {
        session = refreshed;
        break;
      }
      await page.waitForTimeout(500);
    }

    expect(session?.status).toBe('completed');

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

    await expect(page.getByText(/Marketing-Dashboard/)).toBeVisible();
    await expect(
      page.getByRole('button', { name: /Zum Admin-Bereich|To Admin Area/i })
    ).toBeVisible();

    expect(paddleRequestPayload).not.toBeNull();
    expect(paddleRequestPayload?.['coupon_code']).toBe('PERCENT10');

    const messages = await getTestMailbox();
    expect(messages.length).toBeGreaterThan(0);
  });
});

declare global {
  interface Window {
    __openedWindows?: unknown[];
    __paddleEventCallback?: ((event: { name: string }) => void) | null;
    __paddleInitOptions?: unknown;
    __paddleCheckoutConfig?: unknown;
  }
}
