// KueSync — persistent trial store
// © 2026 Krometis Analytics. All rights reserved.
//
// Stores the 7-day trial start OUTSIDE the Companion module folder so re-adding the connection /
// reinstalling can't restart the trial, PLUS a high-water "lastSeen" timestamp so rolling the
// system clock backward can't extend the trial. On macOS: ~/Library/Application Support/KueSync/.
//
// Honest scope: this deters casual tampering. It is NOT tamper-proof — deleting trial.json AND the
// connection config resets the trial, and a sufficiently large forward clock jump expires it early.

import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'

function storeDir() {
  if (process.platform === 'darwin') return path.join(os.homedir(), 'Library', 'Application Support', 'KueSync')
  return path.join(os.homedir(), '.kuesync')
}
export const TRIAL_FILE = path.join(storeDir(), 'trial.json')

function readState() {
  try { return JSON.parse(fs.readFileSync(TRIAL_FILE, 'utf8')) } catch { return {} }
}
function writeState(s) {
  try { fs.mkdirSync(storeDir(), { recursive: true }); fs.writeFileSync(TRIAL_FILE, JSON.stringify({ product: 'kuesync', ...s })); return true }
  catch { return false }
}

export function loadTrialStart() {
  const ts = Number(readState().trialStart)
  return Number.isFinite(ts) ? ts : undefined
}
export function loadLastSeen() {
  const ts = Number(readState().lastSeen)
  return Number.isFinite(ts) ? ts : 0
}
export function persistTrialStart(ts) {
  return writeState({ ...readState(), trialStart: ts })
}
/** Persist lastSeen only if it advances (monotonic high-water mark). */
export function persistLastSeen(ts) {
  const s = readState()
  if (!(Number(ts) > Number(s.lastSeen || 0))) return false
  return writeState({ ...s, lastSeen: ts })
}

/**
 * Resolve the authoritative trial start as the EARLIEST of the persisted file and the config, so
 * clearing any single source can't restart the trial. Writes the result back.
 */
export function resolveTrialStart(configTS, now = Date.now()) {
  const candidates = [loadTrialStart(), configTS].filter((x) => Number.isFinite(x))
  const effective = candidates.length ? Math.min(...candidates) : now
  persistTrialStart(effective)
  return effective
}
