"use client";

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useRouter } from 'next/navigation';
import { useDataProvider, useQueryKeyPrefix } from '@/lib/demo/data-provider-context';

// ---------------------------------------------------------------------------
// Auth hooks
// ---------------------------------------------------------------------------
// Identity is owned by Ory Kratos. `getCurrentUser` reads the honeyDue-side
// profile from the Go API (authenticated via the Kratos session cookie);
// `logout` drives the Kratos browser logout flow.
// ---------------------------------------------------------------------------

export function useCurrentUser() {
  const { auth } = useDataProvider();
  const qk = useQueryKeyPrefix();
  return useQuery({
    queryKey: qk('auth', 'user'),
    queryFn: () => auth.getCurrentUser(),
    retry: false,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

export function useLogout() {
  const queryClient = useQueryClient();
  const router = useRouter();
  const { auth, basePath } = useDataProvider();

  return useMutation({
    mutationFn: () => auth.logout(),
    onSuccess: () => {
      queryClient.clear();
      // In demo mode there is no Kratos session — just route back to /demo.
      // In real mode, auth.logout() already hands the browser off to the
      // Kratos logout flow, so this router.push is only a fallback.
      if (basePath.startsWith('/demo')) {
        router.push('/demo');
      }
    },
  });
}
