/**
 * Local tracking system for PDF transfers
 * Stores transfer history locally (not transmitted)
 */

const STORAGE_KEY = 'transferTracking';
const MAX_ENTRIES = 500; // Cap to prevent unbounded growth

export interface TrackingEntry {
  id: string; // unique identifier
  timestamp: number;
  sourceDomain: string;
  destinationUrl: string;
  pdfSize: number; // bytes
  result: 'success' | 'failure';
  errorMessage?: string; // if result === 'failure'
}

export interface TrackingSummary {
  totalTransfers: number;
  successfulTransfers: number;
  failedTransfers: number;
  lastTransferTime: number | null;
}

/**
 * Add a tracking entry
 */
export async function addTrackingEntry(
  entry: Omit<TrackingEntry, 'id'>
): Promise<void> {
  const entries = await getAllEntries();

  // Add new entry with unique ID
  const newEntry: TrackingEntry = {
    ...entry,
    id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
  };

  entries.unshift(newEntry); // Add to beginning (most recent first)

  // Cap at MAX_ENTRIES
  if (entries.length > MAX_ENTRIES) {
    entries.splice(MAX_ENTRIES);
  }

  await chrome.storage.local.set({ [STORAGE_KEY]: entries });
}

/**
 * Get all tracking entries
 */
export async function getAllEntries(): Promise<TrackingEntry[]> {
  const stored = await chrome.storage.local.get(STORAGE_KEY);
  return stored[STORAGE_KEY] || [];
}

/**
 * Get tracking summary statistics
 */
export async function getTrackingSummary(): Promise<TrackingSummary> {
  const entries = await getAllEntries();

  if (entries.length === 0) {
    return {
      totalTransfers: 0,
      successfulTransfers: 0,
      failedTransfers: 0,
      lastTransferTime: null
    };
  }

  const successfulTransfers = entries.filter((e) => e.result === 'success').length;
  const failedTransfers = entries.filter((e) => e.result === 'failure').length;
  const lastTransferTime = entries[0].timestamp; // First entry is most recent

  return {
    totalTransfers: entries.length,
    successfulTransfers,
    failedTransfers,
    lastTransferTime
  };
}

/**
 * Clear all tracking data
 */
export async function clearTracking(): Promise<void> {
  await chrome.storage.local.remove(STORAGE_KEY);
}

/**
 * Export tracking data as CSV
 */
export function exportAsCSV(entries: TrackingEntry[]): string {
  const headers = [
    'Timestamp',
    'Source Domain',
    'Destination URL',
    'PDF Size (bytes)',
    'Result',
    'Error Message'
  ];

  const rows = entries.map((entry) => [
    new Date(entry.timestamp).toISOString(),
    entry.sourceDomain,
    entry.destinationUrl,
    entry.pdfSize.toString(),
    entry.result,
    entry.errorMessage || ''
  ]);

  const csvLines = [
    headers.join(','),
    ...rows.map((row) => row.map(escapeCSV).join(','))
  ];

  return csvLines.join('\n');
}

/**
 * Escape CSV field
 */
function escapeCSV(field: string): string {
  if (field.includes(',') || field.includes('"') || field.includes('\n')) {
    return `"${field.replace(/"/g, '""')}"`;
  }
  return field;
}
