// 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()

  /**
   * Login with email and password
   * Direct authentication via Cidaas API (no redirect)
   */
  async function login(email: string, password: string) {
    try {
      // Call login endpoint - creates session directly
      await $fetch('/api/auth/login', {
        method: 'POST',
        body: { email, password },
      })

      // Refresh user session
      await fetch()

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

      navigateTo(destination)
    } catch (error) {
      console.error('Login failed:', error)
      throw error
    }
  }

  /**
   * 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
   * Clears session and redirects to homepage
   */
  async function logout() {
    try {
      await $fetch('/api/auth/logout', { method: 'POST' })
      await clear() // Clear client-side state
      navigateTo('/') // Redirect to homepage
    } catch (error) {
      console.error('Logout failed:', error)
      throw error
    }
  }

  /**
   * 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,
  }
}
