'use client';

import { useQuery } from '@tanstack/react-query';

import { apiFetch } from '@/lib/api/client';

export interface OnboardingStatusStep {
  id: string;
  href: string;
  label: string;
  description: string;
  done: boolean;
  auto: boolean;
}

export interface OnboardingStatusPayload {
  steps: OnboardingStatusStep[];
  completed: number;
  total: number;
  percent: number;
  isComplete: boolean;
  nextStep: { id: string; label: string; href: string } | null;
}

/**
 * Shared onboarding-status query. Drives the topbar banner, dashboard tile,
 * and the admin checklist summary. Cached for 60s so all three surfaces
 * share a single fetch on first paint.
 *
 * Defaults to OFF: the endpoint is admin-only (admin.manage_settings), so
 * callers must opt in with `enabled: true` once they've confirmed the user is
 * a super_admin. This prevents a transient 403 (e.g. a stale `isSuperAdmin`
 * during permission hydration) from firing the privileged request for
 * non-admins.
 */
export function useOnboardingStatus(opts: { enabled?: boolean } = {}) {
  return useQuery<OnboardingStatusPayload>({
    queryKey: ['admin', 'onboarding-status'],
    queryFn: () =>
      apiFetch<{ data: OnboardingStatusPayload }>('/api/v1/admin/onboarding/status').then(
        (r) => r.data,
      ),
    staleTime: 60_000,
    enabled: opts.enabled === true,
    retry: false,
  });
}
