import { vi } from 'vitest'

/**
 * UserContext type for WorkOS JWT verification
 * Matches the structure from apps/api/src/identity/auth/jwt-verifier.ts
 */
export interface UserContext {
  workosId: string
  supabaseId: string
  email: string
  firstName?: string
  lastName?: string
  isPlatformAdmin?: boolean
}

/**
 * Mock WorkOS client for testing
 *
 * Usage:
 * ```typescript
 * import { createMockWorkOSClient, TEST_USERS } from '@elevasis/core/test-utils'
 *
 * const mockWorkOS = createMockWorkOSClient({
 *   validTokens: {
 *     'valid-token': {
 *       workosId: TEST_USERS.admin.workos_user_id,
 *       supabaseId: TEST_USERS.admin.id,
 *       email: TEST_USERS.admin.email
 *     }
 *   }
 * })
 *
 * vi.mock('../identity/auth/workos-client', () => ({ workos: mockWorkOS }))
 * ```
 */
export function createMockWorkOSClient(options: {
  validTokens?: Record<string, UserContext>
  shouldFail?: boolean
} = {}) {
  const { validTokens = {}, shouldFail = false } = options

  return {
    userManagement: {
      authenticateWithSessionCookie: vi.fn(async ({ sessionData }: { sessionData: string; cookiePassword?: string }) => {
        if (shouldFail) {
          throw new Error('Authentication failed')
        }

        const userContext = validTokens[sessionData]
        if (!userContext) {
          return null
        }

        return {
          user: {
            id: userContext.workosId,
            email: userContext.email,
            firstName: userContext.firstName,
            lastName: userContext.lastName
          },
          sessionId: 'session_test',
          organizationId: null
        }
      })
    }
  }
}

/**
 * Helper to create mock verifyJWT function
 * This mocks the actual verifyJWT function from jwt-verifier.ts
 *
 * Usage:
 * ```typescript
 * import { createMockVerifyJWT, TEST_USERS } from '@elevasis/core/test-utils'
 *
 * const mockVerifyJWT = createMockVerifyJWT({
 *   'valid-token': {
 *     workosId: TEST_USERS.admin.workos_user_id,
 *     supabaseId: TEST_USERS.admin.id,
 *     email: TEST_USERS.admin.email
 *   }
 * })
 *
 * vi.mock('../identity/auth/jwt-verifier', () => ({
 *   verifyJWT: mockVerifyJWT,
 *   extractToken: vi.fn((header) => header?.replace('Bearer ', ''))
 * }))
 * ```
 */
export function createMockVerifyJWT(
  validTokens: Record<string, UserContext> = {}
): ReturnType<typeof vi.fn> {
  return vi.fn(async (token: string): Promise<UserContext | null> => {
    const userContext = validTokens[token]
    return userContext || null
  })
}

/**
 * Pre-configured mock for extractToken helper
 */
export const mockExtractToken = vi.fn((authHeader?: string): string | null => {
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return null
  }
  return authHeader.slice(7)
})
