/**
 * Document Analytics Service
 * Provides analytics and insights for documents
 */

import {
  getDocumentById,
  getDocumentAuditLogs,
  getDocumentVersions,
  getDocumentComments,
} from '@the-order/database';
import { getLegalMatter, getMatterDocuments } from '@the-order/database';

export interface DocumentAnalytics {
  document_id: string;
  views: number;
  downloads: number;
  edits: number;
  comments: number;
  versions: number;
  last_accessed?: Date;
  most_active_users: Array<{ user_id: string; action_count: number }>;
  access_timeline: Array<{ date: string; count: number }>;
}

/**
 * Get document analytics
 */
export async function getDocumentAnalytics(document_id: string): Promise<DocumentAnalytics> {
  const document = await getDocumentById(document_id);
  if (!document) {
    throw new Error('Document not found');
  }

  const auditLogs = await getDocumentAuditLogs(document_id);
  const versions = await getDocumentVersions(document_id);
  const comments = await getDocumentComments(document_id);

  const views = auditLogs.filter((log) => log.action === 'viewed').length;
  const downloads = auditLogs.filter((log) => log.action === 'downloaded').length;
  const edits = auditLogs.filter((log) => log.action === 'modified').length;

  // Get most active users
  const userActivity: Record<string, number> = {};
  auditLogs.forEach((log) => {
    if (log.performed_by) {
      userActivity[log.performed_by] = (userActivity[log.performed_by] || 0) + 1;
    }
  });

  const most_active_users = Object.entries(userActivity)
    .map(([user_id, action_count]) => ({ user_id, action_count }))
    .sort((a, b) => b.action_count - a.action_count)
    .slice(0, 10);

  // Get access timeline (last 30 days)
  const thirtyDaysAgo = new Date();
  thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

  const recentLogs = auditLogs.filter(
    (log) => new Date(log.performed_at) >= thirtyDaysAgo
  );

  const timelineMap: Record<string, number> = {};
  recentLogs.forEach((log) => {
    const date = new Date(log.performed_at).toISOString().split('T')[0];
    timelineMap[date] = (timelineMap[date] || 0) + 1;
  });

  const access_timeline = Object.entries(timelineMap)
    .map(([date, count]) => ({ date, count }))
    .sort((a, b) => a.date.localeCompare(b.date));

  const last_accessed = auditLogs[0]?.performed_at;

  return {
    document_id,
    views,
    downloads,
    edits,
    comments: comments.length,
    versions: versions.length,
    last_accessed,
    most_active_users,
    access_timeline,
  };
}

/**
 * Get matter analytics
 */
export interface MatterAnalytics {
  matter_id: string;
  total_documents: number;
  total_actions: number;
  document_types: Record<string, number>;
  activity_timeline: Array<{ date: string; count: number }>;
}

export async function getMatterAnalytics(matter_id: string): Promise<MatterAnalytics> {
  const matter = await getLegalMatter(matter_id);
  if (!matter) {
    throw new Error('Matter not found');
  }

  const documents = await getMatterDocuments(matter_id);

  // Get all audit logs for matter documents
  const allAuditLogs = [];
  for (const doc of documents) {
    const logs = await getDocumentAuditLogs(doc.id);
    allAuditLogs.push(...logs);
  }

  // Count document types
  const document_types: Record<string, number> = {};
  documents.forEach((doc) => {
    document_types[doc.type] = (document_types[doc.type] || 0) + 1;
  });

  // Get activity timeline
  const thirtyDaysAgo = new Date();
  thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

  const recentLogs = allAuditLogs.filter(
    (log) => new Date(log.performed_at) >= thirtyDaysAgo
  );

  const timelineMap: Record<string, number> = {};
  recentLogs.forEach((log) => {
    const date = new Date(log.performed_at).toISOString().split('T')[0];
    timelineMap[date] = (timelineMap[date] || 0) + 1;
  });

  const activity_timeline = Object.entries(timelineMap)
    .map(([date, count]) => ({ date, count }))
    .sort((a, b) => a.date.localeCompare(b.date));

  return {
    matter_id,
    total_documents: documents.length,
    total_actions: allAuditLogs.length,
    document_types,
    activity_timeline,
  };
}

