/**
 * Dashboard Summary Hook
 * Provides dashboard data with proper error handling, caching, and loading states
 */

import { useQuery } from "@tanstack/react-query";
import { useAuthSession } from "@/features/auth/services/auth.store";
import { apiClient, queryKeys } from "@/lib/api";
import {
  dashboardSummarySchema,
  type DashboardSummary,
  type DashboardError,
} from "@customer-portal/domain/dashboard";

class DashboardDataError extends Error {
  constructor(
    public code: DashboardError["code"],
    message: string,
    public details?: Record<string, unknown>
  ) {
    super(message);
    this.name = "DashboardDataError";
  }
}

/**
 * Hook for fetching dashboard summary data
 */
export function useDashboardSummary() {
  const { isAuthenticated } = useAuthSession();

  return useQuery<DashboardSummary, DashboardError>({
    queryKey: queryKeys.dashboard.summary(),
    queryFn: async () => {
      if (!isAuthenticated) {
        throw new DashboardDataError(
          "AUTHENTICATION_REQUIRED",
          "Authentication required to fetch dashboard data"
        );
      }

      try {
        const response = await apiClient.GET<DashboardSummary>("/api/me/summary");
        if (!response.data) {
          throw new DashboardDataError("FETCH_ERROR", "Dashboard summary response was empty");
        }
        const parsed = dashboardSummarySchema.safeParse(response.data);
        if (!parsed.success) {
          throw new DashboardDataError(
            "FETCH_ERROR",
            "Dashboard summary response failed validation",
            { issues: parsed.error.issues }
          );
        }
        return parsed.data;
      } catch (error) {
        // Transform API errors to DashboardError format
        if (error instanceof Error) {
          throw new DashboardDataError("FETCH_ERROR", error.message, {
            originalError: error,
          });
        }

        throw new DashboardDataError(
          "UNKNOWN_ERROR",
          "An unexpected error occurred while fetching dashboard data",
          { originalError: error as Record<string, unknown> }
        );
      }
    },
    staleTime: 2 * 60 * 1000, // 2 minutes
    gcTime: 5 * 60 * 1000, // 5 minutes (formerly cacheTime)
    enabled: isAuthenticated,
    retry: (failureCount, error) => {
      // Don't retry authentication errors
      if (error?.code === "AUTHENTICATION_REQUIRED") {
        return false;
      }
      // Retry up to 3 times for other errors
      return failureCount < 3;
    },
    retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000), // Exponential backoff
  });
}
