import type { Page } from '@playwright/test'

type WaitUntilState = 'load' | 'domcontentloaded' | 'networkidle' | 'commit'

type RouteNavigationOptions = {
  waitUntil?: WaitUntilState
  timeoutMs?: number
}

const PLATFORM_AUTH_STORAGE_KEY = 'hypertwist.platform.user.v1'
const E2E_FALLBACK_USER = {
  id: 'e2e_operator_user',
  name: 'E2E Operator',
  email: 'e2e.operator@hypertwist.local',
  authMethod: 'email',
  plan: 'free',
}

async function seedFallbackAuthForProtectedRoutes(page: Page) {
  await page.addInitScript(
    ({ storageKey, userJson }) => {
      try {
        if (!window.localStorage.getItem(storageKey)) {
          window.localStorage.setItem(storageKey, userJson)
        }
      } catch {
        // Fail-open for storage-restricted contexts.
      }
    },
    {
      storageKey: PLATFORM_AUTH_STORAGE_KEY,
      userJson: JSON.stringify(E2E_FALLBACK_USER),
    },
  )
}

export async function gotoAppRoute(
  page: Page,
  routePath: string,
  options: RouteNavigationOptions = {},
) {
  const normalizedPath = routePath.startsWith('/') ? routePath : `/${routePath}`
  if (normalizedPath.startsWith('/app')) {
    await seedFallbackAuthForProtectedRoutes(page)
  }
  await page.goto(normalizedPath, {
    waitUntil: options.waitUntil ?? 'domcontentloaded',
    timeout: options.timeoutMs ?? 30_000,
  })
}
