import type {
  ActivityLogEntry,
  ActivityLogLevel,
  ActivityLogSource,
} from "@/types/activity";

import { save } from '@tauri-apps/plugin-dialog';
import { writeTextFile } from '@tauri-apps/plugin-fs';

const STORAGE_KEY = "lr-openwrt-tool.activity-logs";

export function getActivityLogs(): ActivityLogEntry[] {
  try {
    return JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]");
  } catch {
    return [];
  }
}

export function addActivityLog(input: {
  level: ActivityLogLevel;
  source: ActivityLogSource;
  action: string;
  message: string;
  routerIp?: string;
  vpnIp?: string;
}) {
  const entry: ActivityLogEntry = {
    id: crypto.randomUUID(),
    timestamp: new Date().toISOString(),
    ...input,
  };

  const logs = getActivityLogs();

  localStorage.setItem(
    STORAGE_KEY,
    JSON.stringify([entry, ...logs].slice(0, 500)),
  );

  window.dispatchEvent(new CustomEvent("activity-log-added"));

  return entry;
}

export function clearActivityLogs() {
  localStorage.removeItem(STORAGE_KEY);

  window.dispatchEvent(new CustomEvent("activity-log-added"));
}

export async function exportActivityLogs() {
  const logs = getActivityLogs();

  const filePath = await save({
    title: 'Export Activity Logs',
    defaultPath: `lr-activity-logs-${new Date()
      .toISOString()
      .replace(/:/g, '-')}.json`,
    filters: [
      {
        name: 'JSON',
        extensions: ['json'],
      },
    ],
  });

  if (!filePath) {
    return;
  }

  await writeTextFile(
    filePath,
    JSON.stringify(logs, null, 2),
  );
}