/**
 * Secure authentication token storage
 * 
 * This module provides an abstraction for storing authentication tokens
 * securely using httpOnly cookies via API endpoints.
 */

/**
 * Store authentication token via httpOnly cookie
 */
export async function setAuthToken(token: string): Promise<void> {
  if (typeof window === 'undefined') {
    return
  }

  try {
    // Store in httpOnly cookie via API endpoint
    const response = await fetch('/api/auth/token', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ token }),
    })

    if (!response.ok) {
      throw new Error('Failed to set token')
    }
  } catch (error) {
    console.error('Failed to set auth token:', error)
    // Fallback to sessionStorage if API fails
    sessionStorage.setItem('auth_token', token)
  }
}

/**
 * Get authentication token from httpOnly cookie
 */
export async function getAuthToken(): Promise<string | null> {
  if (typeof window === 'undefined') {
    return null
  }

  try {
    // Try to get from httpOnly cookie via API
    const response = await fetch('/api/auth/token')
    if (response.ok) {
      const data = await response.json()
      return data.token || null
    }
  } catch (error) {
    console.error('Failed to get auth token:', error)
  }

  // Fallback to sessionStorage
  return sessionStorage.getItem('auth_token')
}

/**
 * Synchronous get auth token (for immediate use)
 * Falls back to sessionStorage if cookie not available
 */
export function getAuthTokenSync(): string | null {
  if (typeof window === 'undefined') {
    return null
  }

  // Check sessionStorage first (faster for immediate use)
  return sessionStorage.getItem('auth_token')
}

/**
 * Clear authentication token
 */
export async function clearAuthToken(): Promise<void> {
  if (typeof window === 'undefined') {
    return
  }

  try {
    // Clear httpOnly cookie via API endpoint
    await fetch('/api/auth/token', {
      method: 'DELETE',
    })
  } catch (error) {
    console.error('Failed to clear auth token:', error)
  }

  // Also clear sessionStorage as fallback
  sessionStorage.removeItem('auth_token')
}

/**
 * Remove authentication token (alias for clearAuthToken)
 */
export async function removeAuthToken(): Promise<void> {
  return clearAuthToken()
}

/**
 * Check if user is authenticated
 */
export async function isAuthenticated(): Promise<boolean> {
  const token = await getAuthToken()
  return token !== null
}

/**
 * Synchronous check if user is authenticated
 */
export function isAuthenticatedSync(): boolean {
  return getAuthTokenSync() !== null
}
