import crypto from "node:crypto";
import { config } from "../config";

const ensureSecret = () => {
  if (!config.watcherSecretKey) {
    throw new Error("WATCHER_SECRET_KEY missing");
  }
  return crypto.createHash("sha256").update(config.watcherSecretKey).digest();
};

export const encryptWatcherCookie = (value: string) => {
  const key = ensureSecret();
  const iv = crypto.randomBytes(12);
  const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
  const encrypted = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
  const tag = cipher.getAuthTag();
  return Buffer.concat([iv, tag, encrypted]).toString("base64");
};

export const decryptWatcherCookie = (payload: string) => {
  const key = ensureSecret();
  const source = Buffer.from(payload, "base64");
  const iv = source.subarray(0, 12);
  const tag = source.subarray(12, 28);
  const encrypted = source.subarray(28);
  const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
  decipher.setAuthTag(tag);
  return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString("utf8");
};

export const buildCookieHint = (value: string) => {
  const segments = value
    .split(/[;\n]/)
    .map((entry) => entry.trim())
    .filter(Boolean)
    .slice(0, 2)
    .map((entry) => {
      const [name] = entry.split("=", 1);
      return `${name}=...`;
    });
  return segments.length > 0 ? segments.join("; ") : "Cookie kayitli";
};
