/**
 * Test Helper Utilities
 *
 * Provides utilities for automated testing (Playwright, Vitest E2E)
 *
 * ⚠️ IMPORTANT: These utilities should ONLY be used in test environments.
 * Never use test credentials in production!
 */

/**
 * Get test user credentials from environment variables
 *
 * @throws Error if test credentials are not configured
 * @returns Test user email and password
 *
 * @example
 * ```typescript
 * // In a Playwright test
 * import { getTestCredentials } from '~/server/utils/test-helpers'
 *
 * const { email, password } = getTestCredentials()
 * await page.fill('[name="email"]', email)
 * await page.fill('[name="password"]', password)
 * ```
 */
export function getTestCredentials() {
  const config = useRuntimeConfig()

  const email = config.testUser.email
  const password = config.testUser.password

  if (!email || !password) {
    throw new Error(
      'Test credentials not configured. Please set TEST_USER_EMAIL and TEST_USER_PASSWORD in .env'
    )
  }

  // Security check: Warn if used in production
  if (process.env.NODE_ENV === 'production') {
    console.warn(
      '⚠️  WARNING: Test credentials are being used in production environment! This is a security risk.'
    )
  }

  return {
    email,
    password,
  }
}

/**
 * Check if test credentials are configured
 *
 * @returns true if test credentials are available
 *
 * @example
 * ```typescript
 * if (hasTestCredentials()) {
 *   // Run authenticated tests
 *   const { email, password } = getTestCredentials()
 *   // ... test login flow
 * } else {
 *   console.log('Skipping authenticated tests - no test credentials configured')
 * }
 * ```
 */
export function hasTestCredentials(): boolean {
  const config = useRuntimeConfig()
  return !!(config.testUser.email && config.testUser.password)
}

/**
 * API endpoint to get test credentials
 * ⚠️ ONLY available in development mode
 *
 * This endpoint allows tests to fetch credentials dynamically.
 * It's automatically disabled in production.
 *
 * GET /api/test/credentials
 * Returns: { email: string, password: string }
 */
export function createTestCredentialsEndpoint() {
  return defineEventHandler((event) => {
    // SECURITY: Only allow in development
    if (process.env.NODE_ENV === 'production') {
      throw createError({
        statusCode: 404,
        statusMessage: 'Not Found',
      })
    }

    try {
      const credentials = getTestCredentials()
      return credentials
    } catch (error) {
      throw createError({
        statusCode: 500,
        statusMessage:
          error instanceof Error ? error.message : 'Test credentials not configured',
      })
    }
  })
}
