/**
 * Document Optimization Service
 * Handles performance optimization and caching
 */

import { getDocumentById, listDocuments } from '@the-order/database';
import { getDocumentVersions } from '@the-order/database';

// Simple in-memory cache (in production, use Redis)
const documentCache = new Map<string, { data: any; timestamp: number }>();
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes

/**
 * Get document with caching
 */
export async function getDocumentCached(document_id: string): Promise<any> {
  const cached = documentCache.get(document_id);
  if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
    return cached.data;
  }

  const document = await getDocumentById(document_id);
  if (document) {
    documentCache.set(document_id, { data: document, timestamp: Date.now() });
  }

  return document;
}

/**
 * Invalidate document cache
 */
export function invalidateDocumentCache(document_id: string): void {
  documentCache.delete(document_id);
}

/**
 * Batch load documents
 */
export async function batchLoadDocuments(
  document_ids: string[]
): Promise<Map<string, any>> {
  const results = new Map<string, any>();

  // Check cache first
  const uncached: string[] = [];
  for (const id of document_ids) {
    const cached = documentCache.get(id);
    if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
      results.set(id, cached.data);
    } else {
      uncached.push(id);
    }
  }

  // Load uncached documents
  if (uncached.length > 0) {
    // In a real implementation, you'd use a batch query
    for (const id of uncached) {
      const doc = await getDocumentById(id);
      if (doc) {
        results.set(id, doc);
        documentCache.set(id, { data: doc, timestamp: Date.now() });
      }
    }
  }

  return results;
}

/**
 * Optimize document query with pagination
 */
export interface PaginatedDocuments {
  documents: any[];
  total: number;
  page: number;
  page_size: number;
  has_more: boolean;
}

export async function getPaginatedDocuments(
  page = 1,
  page_size = 50,
  filters?: { type?: string; matter_id?: string }
): Promise<PaginatedDocuments> {
  const offset = (page - 1) * page_size;

  // In a real implementation, you'd use a more efficient query
  const allDocuments = await listDocuments(filters?.type, 10000, 0);
  const filtered = filters?.matter_id
    ? allDocuments // Would filter by matter_id in real query
    : allDocuments;

  const total = filtered.length;
  const documents = filtered.slice(offset, offset + page_size);

  return {
    documents,
    total,
    page,
    page_size,
    has_more: offset + page_size < total,
  };
}

/**
 * Preload document versions
 */
export async function preloadDocumentVersions(document_id: string): Promise<void> {
  // Preload versions into cache
  const versions = await getDocumentVersions(document_id);
  // Cache versions (simplified - in production, use proper caching)
  documentCache.set(`versions:${document_id}`, {
    data: versions,
    timestamp: Date.now(),
  });
}

/**
 * Clear all caches (for testing/maintenance)
 */
export function clearAllCaches(): void {
  documentCache.clear();
}

