/**
 * Document Export Service
 * Handles document export and reporting
 */

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

export interface ExportOptions {
  format: 'pdf' | 'docx' | 'txt' | 'json';
  include_versions?: boolean;
  include_audit_log?: boolean;
  include_metadata?: boolean;
}

/**
 * Export document
 */
export async function exportDocument(
  document_id: string,
  options: ExportOptions
): Promise<{ content: Buffer | string; mime_type: string; filename: string }> {
  const document = await getDocumentById(document_id);
  if (!document) {
    throw new Error('Document not found');
  }

  let content: Buffer | string = '';
  let mime_type = '';
  let filename = '';

  if (options.format === 'json') {
    const exportData: any = {
      document: {
        id: document.id,
        title: document.title,
        type: document.type,
        content: document.content,
        created_at: document.created_at,
        updated_at: document.updated_at,
      },
    };

    if (options.include_versions) {
      const versions = await getDocumentVersions(document_id);
      exportData.versions = versions;
    }

    if (options.include_audit_log) {
      const auditLogs = await getDocumentAuditLogs(document_id);
      exportData.audit_log = auditLogs;
    }

    if (options.include_metadata) {
      exportData.metadata = {
        classification: document.classification,
        extracted_data: document.extracted_data,
      };
    }

    content = JSON.stringify(exportData, null, 2);
    mime_type = 'application/json';
    filename = `${document.title.replace(/[^a-z0-9]/gi, '_')}.json`;
  } else if (options.format === 'txt') {
    content = document.content || '';
    mime_type = 'text/plain';
    filename = `${document.title.replace(/[^a-z0-9]/gi, '_')}.txt`;
  } else if (options.format === 'pdf') {
    // TODO: Implement PDF generation using a library like pdfkit or puppeteer
    content = Buffer.from('PDF generation not yet implemented');
    mime_type = 'application/pdf';
    filename = `${document.title.replace(/[^a-z0-9]/gi, '_')}.pdf`;
  } else if (options.format === 'docx') {
    // TODO: Implement DOCX generation using a library like docx
    content = Buffer.from('DOCX generation not yet implemented');
    mime_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
    filename = `${document.title.replace(/[^a-z0-9]/gi, '_')}.docx`;
  }

  return { content, mime_type, filename };
}

/**
 * Export matter with all documents
 */
export async function exportMatter(
  matter_id: string,
  options: ExportOptions
): Promise<{ content: Buffer | string; mime_type: string; filename: string }> {
  const matter = await getLegalMatter(matter_id);
  if (!matter) {
    throw new Error('Matter not found');
  }

  const documents = await getMatterDocuments(matter_id);

  const exportData: any = {
    matter: {
      id: matter.id,
      matter_number: matter.matter_number,
      title: matter.title,
      description: matter.description,
      status: matter.status,
    },
    documents: await Promise.all(
      documents.map(async (doc) => {
        const docData: any = {
          id: doc.id,
          title: doc.title,
          type: doc.type,
        };

        if (options.include_versions) {
          const versions = await getDocumentVersions(doc.id);
          docData.versions = versions;
        }

        return docData;
      })
    ),
  };

  const content = JSON.stringify(exportData, null, 2);
  const mime_type = 'application/json';
  const filename = `${matter.matter_number.replace(/[^a-z0-9]/gi, '_')}_export.json`;

  return { content, mime_type, filename };
}

/**
 * Generate compliance report
 */
export interface ComplianceReport {
  document_id: string;
  total_actions: number;
  access_log: any[];
  retention_status?: any;
  audit_summary: any;
}

export async function generateComplianceReport(
  document_id: string
): Promise<ComplianceReport> {
  const document = await getDocumentById(document_id);
  if (!document) {
    throw new Error('Document not found');
  }

  const auditLogs = await getDocumentAuditLogs(document_id);

  // Get access log (viewed, downloaded, etc.)
  const accessLog = auditLogs.filter(
    (log) => ['viewed', 'downloaded', 'exported', 'printed'].includes(log.action)
  );

  // Get retention status if applicable
  const { getDocumentRetentionRecord } = await import('@the-order/database');
  const retentionRecord = await getDocumentRetentionRecord(document_id);

  return {
    document_id,
    total_actions: auditLogs.length,
    access_log: accessLog,
    retention_status: retentionRecord,
    audit_summary: {
      created: auditLogs.find((log) => log.action === 'created'),
      last_accessed: accessLog[0],
      total_accesses: accessLog.length,
    },
  };
}

