import { request as playwrightRequest } from '@playwright/test';

type BillingMode = 'modern' | 'classic';

const DEFAULT_BILLING_API_URL = 'https://billing-api-test.kinnovis.com';

// `KINNOVIS_BILLING=1` runs the suite against the modern (Kinnovis) billing system; any other value
// (including `0` and unset) is classic. Mirrors the manager SPA's `isKinnovisBillingUser` switch: in
// modern mode booking create/cancel move from the manager API to the billing API.
function resolveBillingMode(): BillingMode {
  return process.env.KINNOVIS_BILLING === '1' ? 'modern' : 'classic';
}

export function isModernBillingMode(): boolean {
  return resolveBillingMode() === 'modern';
}

// Calls one of billing's unauthenticated e2e routes; `action` describes the intent in failure
// messages, e.g. `Failed to <action> via <url>: <status> <body>`.
async function callBillingE2eRoute(path: string, action: string): Promise<void> {
  const baseURL = process.env.BILLING_API_URL ?? DEFAULT_BILLING_API_URL;
  const ctx = await playwrightRequest.newContext({
    baseURL,
    extraHTTPHeaders: { Accept: 'application/json' },
  });

  try {
    const response = await ctx.get(path);

    if (!response.ok()) {
      throw new Error(`Failed to ${action} via ${baseURL}${path}: ${response.status()} ${await response.text()}`);
    }
  } finally {
    await ctx.dispose();
  }
}

// Pins the shared QA storeroom tenant to the resolved billing mode via billing's unauthenticated
// e2e reset route. Used by global setup so runs are deterministic regardless of the mode a
// previous run left the environment in.
export async function pinBillingMode(): Promise<void> {
  const mode = resolveBillingMode();
  await callBillingE2eRoute(`/e2e/storeroom/${mode}`, `pin billing mode to "${mode}"`);
}

// The modern billing system only learns about CLASSIC catalog changes through
// `kin:catalog:import`, which is scheduled every five minutes — far too slow for a test
// that creates a unit type (or discount, product, ...) and books it seconds later. This
// triggers the import synchronously via billing's e2e route; the route serializes
// concurrent callers server-side, so parallel workers can call it freely.
// No-op in classic mode, where the billing catalog is not involved.
export async function syncBillingCatalog(): Promise<void> {
  if (!isModernBillingMode()) {
    return;
  }

  await callBillingE2eRoute('/e2e/storeroom/import', 'sync billing catalog');
}
