import { generateKeyPairSync, sign } from 'node:crypto';
import type { Page } from '@playwright/test';

function base64Url(value: string | Buffer): string {
  return Buffer.from(value).toString('base64url');
}

export function createTestProEntitlement(now = Date.now()) {
  const { privateKey, publicKey } = generateKeyPairSync('ed25519');
  const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString();
  const issuedAt = Math.floor(now / 1000);
  const payload = {
    version: 1,
    tier: 'pro',
    source: 'predefined',
    licenseFingerprint: 'test:pro:0001',
    issuedAt,
    refreshAfter: issuedAt + 30 * 86_400,
    validUntil: issuedAt + 120 * 86_400,
    refreshHandle: 'e2e-fixture',
  };
  const encodedPayload = base64Url(JSON.stringify(payload));
  const signingInput = `learnitive1.${encodedPayload}`;
  const signature = sign(null, Buffer.from(signingInput), privateKey);
  return {
    entitlement: `${signingInput}.${base64Url(signature)}`,
    publicKey: publicKeyPem,
  };
}

export async function installProActivationRoute(page: Page) {
  const fixture = createTestProEntitlement();
  let activations = 0;
  await page.route('**/api/license/activate', async (route) => {
    activations += 1;
    const body = route.request().postDataJSON() as { licenseKey?: string };
    if (!body.licenseKey) {
      await route.fulfill({ status: 401, contentType: 'application/json', body: JSON.stringify({ error: 'invalid_license' }) });
      return;
    }
    await route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify(fixture),
    });
  });
  return { get activations() { return activations; } };
}

export async function activateProFromAiLauncher(page: Page) {
  await page.getByRole('button', { name: 'Open Learnitive AI' }).click();
  const ai = page.getByTestId('interactive-ai-overlay');
  await ai.getByRole('button', { name: 'AI settings' }).click();
  await ai.getByRole('button', { name: 'Activate Pro' }).click();
  const dialog = page.getByTestId('interactive-pro-dialog');
  await dialog.getByLabel('Licence key').fill('LEARNITIVE-PRO-E2E-TEST');
  await dialog.getByRole('button', { name: 'Activate Pro' }).click();
  await page.getByText('Learnitive Pro is active').waitFor();
  await page.keyboard.press('Escape');
  await ai.getByRole('button', { name: 'Close Learnitive AI' }).click();
}
