'use client';

import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import type { EcoDmsDocument, EcoDmsClassification } from '@/types/integrations';

/** Query key factory */
export const documentsKeys = {
  all: ['documents'] as const,
  list: (filters?: { classification?: string; search?: string }) =>
    [...documentsKeys.all, 'list', filters] as const,
  classifications: ['documents', 'classifications'] as const,
  recent: ['documents', 'recent'] as const,
};

interface FetchDocumentsParams {
  classification?: string;
  search?: string;
  limit?: number;
}

/**
 * Fetch ecoDMS documents
 */
async function fetchDocuments(params?: FetchDocumentsParams): Promise<EcoDmsDocument[]> {
  const queryParams: Record<string, string | number | boolean | undefined> = {};
  if (params?.classification) queryParams.classification = params.classification;
  if (params?.search) queryParams.query = params.search;
  if (params?.limit) queryParams.pageSize = params.limit;

  const response = await api.get<{ documents: EcoDmsDocument[] } | EcoDmsDocument[]>(
    '/integrations/ecodms/documents',
    { params: queryParams },
  );
  return Array.isArray(response) ? response : response.documents;
}

/**
 * Fetch document classifications
 */
async function fetchClassifications(): Promise<EcoDmsClassification[]> {
  const response = await api.get<{ classifications: EcoDmsClassification[] } | EcoDmsClassification[]>(
    '/integrations/ecodms/classifications',
  );
  return Array.isArray(response) ? response : response.classifications;
}

/**
 * Fetch recently added documents
 */
async function fetchRecentDocuments(limit = 5): Promise<EcoDmsDocument[]> {
  return fetchDocuments({ limit });
}

/**
 * Hook to fetch ecoDMS documents
 */
export function useDocuments(params?: FetchDocumentsParams) {
  return useQuery({
    queryKey: documentsKeys.list(params),
    queryFn: () => fetchDocuments(params),
    staleTime: 30 * 1000,
    refetchOnWindowFocus: true,
  });
}

/**
 * Hook to fetch document classifications
 */
export function useClassifications() {
  return useQuery({
    queryKey: documentsKeys.classifications,
    queryFn: fetchClassifications,
    staleTime: 60 * 1000,
  });
}

/**
 * Hook to fetch recently added documents
 */
export function useRecentDocuments(limit = 5) {
  return useQuery({
    queryKey: documentsKeys.recent,
    queryFn: () => fetchRecentDocuments(limit),
    staleTime: 30 * 1000,
    refetchOnWindowFocus: true,
  });
}

/**
 * Format file size for display
 */
export function formatDocumentSize(bytes: number): string {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
}
