// composables/useAuth.ts

/**
 * Authentication composable
 *
 * Wrapper around nuxt-auth-utils useUserSession() with convenience methods
 *
 * Usage:
 * const { user, loggedIn, login, logout } = useAuth()
 */

export function useAuth() {
  const { loggedIn, user, clear, fetch } = useUserSession()
  const { fetchRoleStatus } = useActiveRole()

  /**
   * Login with email and password
   * Direct authentication via Cidaas API (no redirect)
   */
  async function login(email: string, password: string) {
    // Call login endpoint - creates session directly
    const response = await $fetch<{ success: boolean; message?: string }>('/api/auth/login', {
      method: 'POST',
      body: { email, password },
      // Don't throw on 4xx/5xx, we handle the response ourselves
      ignoreResponseError: true,
    })

    // Check if login was successful
    if (!response.success) {
      // Throw error with the server's message (contains German text with umlauts)
      const error: any = new Error(response.message || 'Login failed')
      error.data = response
      error.statusCode = 401
      throw error
    }

    // Refresh user session
    await fetch()

    // Fetch user roles immediately after login
    await fetchRoleStatus()

    // Redirect to products page or saved destination
    const redirectAfterLogin = useCookie('redirect_after_login')
    const destination = redirectAfterLogin.value || '/'
    redirectAfterLogin.value = null // Clear cookie

    navigateTo(destination)
  }

  /**
   * Register new user
   */
  async function register(data: {
    email: string
    password: string
    firstName: string
    lastName: string
  }) {
    try {
      const result = await $fetch('/api/auth/register', {
        method: 'POST',
        body: data,
      })

      return result
    } catch (error) {
      console.error('Registration failed:', error)
      throw error
    }
  }

  /**
   * Logout
   * Performs Single Sign-Out at Cidaas and clears local session
   * Redirects to logout confirmation page
   */
  async function logout() {
    try {
      // Call logout endpoint (performs Cidaas SSO + clears session)
      await $fetch('/api/auth/logout', { method: 'POST' })

      // Clear client-side state
      await clear()

      // Redirect to logout confirmation page (with auto-redirect to homepage)
      navigateTo('/logout')
    } catch (error) {
      console.error('Logout failed:', error)
      // Even on error, clear local state and redirect
      await clear()
      navigateTo('/logout')
    }
  }

  /**
   * Refresh user data from server
   */
  async function refreshUser() {
    try {
      await fetch() // Re-fetch session from server
    } catch (error) {
      console.error('Refresh user failed:', error)
    }
  }

  return {
    user,
    loggedIn,
    login,
    register,
    logout,
    refreshUser,
  }
}
