import fs from "fs";
import path from "path";
import crypto from "crypto";

const KEY_FILE = path.resolve(process.cwd(), "network-backup-key.json");
const CONFIG_FILE = path.resolve(process.cwd(), "network-sync-config.json");

export interface NetworkSyncConfig {
  enabled: boolean;
  syncHour: number;
  sourceUrl: string;
  apiKey: string;
  lastSyncAt: string | null;
  lastSyncStatus: string | null;
  lastSyncError: string | null;
}

export function getOrCreateApiKey(): string {
  if (fs.existsSync(KEY_FILE)) {
    try {
      const data = JSON.parse(fs.readFileSync(KEY_FILE, "utf8"));
      if (data.apiKey) return data.apiKey;
    } catch {}
  }
  const key = crypto.randomUUID();
  fs.writeFileSync(KEY_FILE, JSON.stringify({ apiKey: key }), "utf8");
  return key;
}

export function regenerateApiKey(): string {
  const key = crypto.randomUUID();
  fs.writeFileSync(KEY_FILE, JSON.stringify({ apiKey: key }), "utf8");
  return key;
}

export function readSyncConfig(): NetworkSyncConfig {
  if (fs.existsSync(CONFIG_FILE)) {
    try {
      return JSON.parse(fs.readFileSync(CONFIG_FILE, "utf8"));
    } catch {}
  }
  return {
    enabled: false,
    syncHour: 0,
    sourceUrl: "",
    apiKey: "",
    lastSyncAt: null,
    lastSyncStatus: null,
    lastSyncError: null,
  };
}

export function writeSyncConfig(patch: Partial<NetworkSyncConfig>): NetworkSyncConfig {
  const current = readSyncConfig();
  const updated = { ...current, ...patch };
  fs.writeFileSync(CONFIG_FILE, JSON.stringify(updated, null, 2), "utf8");
  return updated;
}
