'use client';

import { useSession } from '@/lib/auth/client';
import type { AuthUser, AuthSession } from '@/types/auth';

interface UseAuthReturn {
  user: AuthUser | null;
  session: AuthSession | null;
  isLoading: boolean;
  isAuthenticated: boolean;
}

/**
 * Hook that wraps Better Auth's useSession and exposes a typed user + session.
 */
export function useAuth(): UseAuthReturn {
  const { data: session, isPending } = useSession();

  const user: AuthUser | null = session?.user
    ? {
        id: session.user.id,
        email: session.user.email,
        name: session.user.name,
        image: session.user.image ?? null,
        emailVerified: session.user.emailVerified,
        createdAt: session.user.createdAt,
        updatedAt: session.user.updatedAt,
      }
    : null;

  const typedSession: AuthSession | null = session
    ? {
        id: session.session.id,
        userId: session.session.userId,
        token: session.session.token,
        expiresAt: session.session.expiresAt,
        ipAddress: session.session.ipAddress ?? null,
        userAgent: session.session.userAgent ?? null,
        createdAt: session.session.createdAt,
        updatedAt: session.session.updatedAt,
        user,
      }
    : null;

  return {
    user,
    session: typedSession,
    isLoading: isPending,
    isAuthenticated: !!user,
  };
}
