import crypto from "crypto";
import Redis from "ioredis";
import Database from "better-sqlite3";
import { logger } from "./logger";

const ttlSeconds = 7 * 24 * 3600;
let redis: Redis | null = null;
let db: Database.Database | null = null;

export function buildDedupKey(source: string, deviceId: string, metric: string, ts: number, value: unknown) {
  const hash = crypto.createHash("sha256").update(JSON.stringify(value ?? "")).digest("hex").slice(0, 12);
  return `${source}:${deviceId}:${metric}:${ts}:${hash}`;
}

export function initDedupStore() {
  const redisUrl = process.env.REDIS_URL;
  if (redisUrl) {
    redis = new Redis(redisUrl);
    logger.info({ redisUrl }, "Dedup store: Redis");
    return;
  }

  const dbPath = process.env.DEDUP_DB_PATH || "/data/dedup.sqlite";
  db = new Database(dbPath);
  db.exec("CREATE TABLE IF NOT EXISTS dedup (key TEXT PRIMARY KEY, ts INTEGER)");
  logger.info({ dbPath }, "Dedup store: SQLite");
}

export async function isDuplicate(key: string): Promise<boolean> {
  if (redis) {
    const result = await redis.set(key, "1", "NX", "EX", ttlSeconds);
    return result !== "OK";
  }
  if (!db) {
    initDedupStore();
  }
  try {
    const stmt = db!.prepare("INSERT INTO dedup (key, ts) VALUES (?, ?)");
    stmt.run(key, Date.now());
    return false;
  } catch {
    return true;
  }
}


export function cleanupDedup() {
  if (!db) return;
  const ttlMs = 7 * 24 * 3600 * 1000;
  const cutoff = Date.now() - ttlMs;
  try {
    db.prepare("DELETE FROM dedup WHERE ts < ?").run(cutoff);
  } catch {}
}
