// Where the site keeps what changes at runtime: CMS content (content/*.json) and private data
// (quote requests, subscribers, quote attachments).
//
// Two backends with the same functions:
//  - "fs"   (local dev, cPanel/Node server): files in content/ and data/, as before.
//  - "blob" (Vercel, where the disk is read-only and every function starts fresh): Vercel Blob.
//
// Blob is file storage, not a database. Measured on this store: list() and head() are always current,
// but reading a file that was OVERWRITTEN can return the previous content for many seconds. So in Blob
// nothing is ever overwritten — every change is a NEW file with a unique name, and the newest one wins:
//  · content:  state/content/<name>/<time>-<rand>.json      (newest = current; the older ones are the history, last 20)
//  · records:  state/data/<collection>/<id>/<time>-<rand>     (one folder per quote / subscriber; every change is a new
//              version, the newest wins; old versions are pruned to the last 5)
//    Two writers never create the SAME file name: measured here, when several requests race to create one name,
//    the losers' attempts leave it unreadable for a while. So ids that need no coordination are used in Blob
//    (quote numbers like MK-261112-7KQF instead of a running counter).
//  · files:    state/data/files/<random>                     (quote attachments)
// Until something is saved from the admin, content comes from the repo copy (content/*.json).
//
// Private data (records, files): in a private store when PRIVATE_BLOB_READ_WRITE_TOKEN is set; otherwise in the
// public store ENCRYPTED with AES-256-GCM — useless without the key (DATA_SECRET, or derived from BLOB_READ_WRITE_TOKEN).
//
// Mode: STORAGE=fs|blob; default "blob" on Vercel (VERCEL=1), "fs" everywhere else.
// STATE_PREFIX separates environments: "state" (production), "state-preview" (Vercel previews), state-test (local tests).

import './env.mjs'
import fs from 'node:fs/promises'
import { existsSync, statSync } from 'node:fs'
import path from 'node:path'
import crypto from 'node:crypto'
import { fileURLToPath } from 'node:url'

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
export const CONTENT_DIR = path.join(ROOT, 'content')
export const DATA_DIR = path.join(ROOT, 'data')
const HISTORY_DIR = path.join(CONTENT_DIR, '.history')
const FILES_DIR = path.join(DATA_DIR, 'quote-files')
const HISTORY_KEEP = 20

export const storageMode = () => {
  const m = (process.env.STORAGE || '').toLowerCase()
  if (m === 'fs' || m === 'blob') return m
  return process.env.VERCEL ? 'blob' : 'fs'
}
/** Production uses state/; Vercel preview deployments get their own folder so tests never mix with real data. */
const PREFIX = () => (process.env.STATE_PREFIX || (process.env.VERCEL_ENV === 'preview' ? 'state-preview' : 'state')).replace(/^\/+|\/+$/g, '')
const publicToken = () => process.env.BLOB_READ_WRITE_TOKEN || ''
const privateToken = () => process.env.PRIVATE_BLOB_READ_WRITE_TOKEN || ''
/** where private data lives: 'disk', a 'private' Blob store, or 'encrypted' files in the public store */
export const dataProtection = () => (storageMode() === 'blob' ? (privateToken() ? 'private' : 'encrypted') : 'disk')

const blob = () => import('@vercel/blob')
const json = (v) => Buffer.from(JSON.stringify(v, null, 1) + '\n')
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const alreadyExists = (e) => /already exists/i.test(e?.message || '')
const stamp = () => new Date().toISOString().replace(/[:.]/g, '-')

// ---------- encryption (private data in the public store) ----------
// Key: DATA_SECRET; without it, derived from BLOB_READ_WRITE_TOKEN. Decryption tries both, so data written
// before DATA_SECRET was set (or after it was removed) stays readable.
const derive = (secret) => Buffer.from(crypto.hkdfSync('sha256', secret, 'maksan-data', 'aes-256-gcm', 32))
let keysCache = null
function keys() {
  if (keysCache) return keysCache
  const secrets = [process.env.DATA_SECRET, publicToken()].filter(Boolean)
  if (!secrets.length) throw new Error('Lipsește DATA_SECRET / BLOB_READ_WRITE_TOKEN pentru criptarea datelor')
  keysCache = secrets.map(derive)
  return keysCache
}
const key = () => keys()[0]
function encrypt(buf) {
  const iv = crypto.randomBytes(12)
  const c = crypto.createCipheriv('aes-256-gcm', key(), iv)
  const body = Buffer.concat([c.update(buf), c.final()])
  return Buffer.concat([Buffer.from('MKS1'), iv, c.getAuthTag(), body])
}
function decrypt(buf) {
  if (buf.subarray(0, 4).toString() !== 'MKS1') throw new Error('Fișier de date necunoscut')
  for (const k of keys()) {
    try {
      const d = crypto.createDecipheriv('aes-256-gcm', k, buf.subarray(4, 16))
      d.setAuthTag(buf.subarray(16, 32))
      return Buffer.concat([d.update(buf.subarray(32)), d.final()])
    } catch {
      /* next key */
    }
  }
  throw new Error('Datele nu pot fi decriptate (DATA_SECRET diferit de cel folosit la salvare)')
}

/** Private data in Blob: store/access/token + (de)serialization. */
const priv = () =>
  privateToken()
    ? { access: 'private', token: privateToken(), ext: '.json', wrap: (b) => b, unwrap: (b) => b, type: 'application/json' }
    : { access: 'public', token: publicToken(), ext: '.enc', wrap: encrypt, unwrap: decrypt, type: 'application/octet-stream' }

/** Every blob under a prefix (all pages). */
async function listAll(prefix, token) {
  const { list } = await blob()
  const out = []
  let cursor
  do {
    const r = await list({ prefix, token, cursor, limit: 1000 })
    out.push(...r.blobs)
    cursor = r.hasMore ? r.cursor : undefined
  } while (cursor)
  return out
}

/**
 * Contents of an immutable blob (never overwritten → never stale), cached by URL.
 * Read from the origin (useCache:false): through the CDN a file created a moment ago can still answer 404.
 */
const bodies = new Map()
async function fetchBlob(b, access, token) {
  if (bodies.has(b.url)) return bodies.get(b.url)
  const { get } = await blob()
  for (let i = 0; i < 10; i++) {
    const r = await get(b.pathname, { access, token, useCache: false }).catch(() => null)
    if (r?.statusCode === 200) {
      const buf = Buffer.from(await new Response(r.stream).arrayBuffer())
      if (bodies.size > 2000) bodies.clear()
      bodies.set(b.url, buf)
      return buf
    }
    await sleep(150 + i * 100)
  }
  throw new Error(`Nu pot citi ${b.pathname}`)
}

/** Runs fn over items, `n` at a time. */
async function pool(items, n, fn) {
  const out = new Array(items.length)
  let i = 0
  await Promise.all(
    Array.from({ length: Math.min(n, items.length) }, async () => {
      while (i < items.length) {
        const k = i++
        out[k] = await fn(items[k])
      }
    }),
  )
  return out
}

/** Groups blobs by the first path segment after `prefix` → Map(name → versions sorted oldest→newest). */
function group(blobs, prefix) {
  const map = new Map()
  for (const b of blobs) {
    const name = b.pathname.slice(prefix.length).split('/')[0]
    if (!map.has(name)) map.set(name, [])
    map.get(name).push(b)
  }
  for (const l of map.values()) l.sort((a, b) => a.pathname.localeCompare(b.pathname))
  return map
}

// ---------- content (CMS documents) ----------
let contentIndex = { at: 0, map: null } // one list() for all documents, kept a few seconds per instance
const INDEX_MS = 20_000

async function contentBlobs(fresh) {
  if (!fresh && contentIndex.map && Date.now() - contentIndex.at < INDEX_MS) return contentIndex.map
  const prefix = `${PREFIX()}/content/`
  const map = group(await listAll(prefix, publicToken()), prefix)
  contentIndex = { at: Date.now(), map }
  return map
}

/**
 * Raw JSON of a content document, or null when it doesn't exist.
 * `fresh`: skip the short per-instance cache (admin reads right after a save).
 */
export async function readContentRaw(name, { fresh = false } = {}) {
  if (storageMode() === 'blob') {
    const versions = (await contentBlobs(fresh)).get(name)
    if (versions?.length) return fetchBlob(versions.at(-1), 'public', publicToken())
  }
  // disk, or nothing saved from the admin yet → the version bundled with the site
  const f = path.join(CONTENT_DIR, `${name}.json`)
  return existsSync(f) ? fs.readFile(f) : null
}

export async function readContent(name, fallback, opts) {
  const b = await readContentRaw(name, opts)
  return b ? JSON.parse(b.toString('utf8')) : fallback
}

/** Saves a content document; the previous versions stay as history (last 20). */
export async function writeContent(name, value) {
  if (storageMode() === 'fs') {
    const file = path.join(CONTENT_DIR, `${name}.json`)
    if (existsSync(file)) {
      await fs.mkdir(HISTORY_DIR, { recursive: true })
      await fs.copyFile(file, path.join(HISTORY_DIR, `${name}-${stamp()}.json`))
      const old = (await fs.readdir(HISTORY_DIR)).filter((f) => f.startsWith(`${name}-`)).sort()
      for (const f of old.slice(0, Math.max(0, old.length - HISTORY_KEEP))) await fs.unlink(path.join(HISTORY_DIR, f))
    }
    const tmp = `${file}.${process.pid}.tmp`
    await fs.writeFile(tmp, json(value))
    await fs.rename(tmp, file)
    return
  }
  const { put, del } = await blob()
  const token = publicToken()
  const body = json(value)
  const r = await put(`${PREFIX()}/content/${name}/${stamp()}-${crypto.randomBytes(3).toString('hex')}.json`, body, {
    access: 'public',
    token,
    contentType: 'application/json; charset=utf-8',
    addRandomSuffix: false,
    allowOverwrite: false,
    cacheControlMaxAge: 60 * 60 * 24 * 365, // a version never changes
  })
  bodies.set(r.url, body)
  const versions = (await contentBlobs(true)).get(name) ?? []
  if (versions.length > HISTORY_KEEP + 1) await del(versions.slice(0, versions.length - HISTORY_KEEP - 1).map((b) => b.url), { token }).catch(() => undefined)
}

/** Change marker for derived caches (SEO data): file mtimes on disk, the content index age in Blob. */
export function contentVersion(names) {
  if (storageMode() === 'fs') {
    return names
      .map((n) => {
        const f = path.join(CONTENT_DIR, `${n}.json`)
        return existsSync(f) ? String(statSync(f).mtimeMs) : '0'
      })
      .join(':')
  }
  return `${Math.floor(Date.now() / INDEX_MS)}`
}

// ---------- private records (quotes, subscribers) ----------
// Same API on disk and in Blob:
//   listRecords(col)                          → all records
//   getRecord(col, id)                        → record | null
//   createRecord(col, id, record)             → record | null (null: a record with this id already exists)
//   updateRecord(col, id, fn)                 → record | null  (fn changes the record in place; return false = no change)
//   deleteRecord(col, id)                     → removed record | null
// On disk a collection is one file, data/<col>.json (as before), written one change at a time.
// KEYS: which field of the record is its id.

const KEYS = { quotes: 'id', subscribers: 'email' }
const blobId = (col, id) => (col === 'subscribers' ? crypto.createHash('sha256').update(String(id)).digest('hex').slice(0, 32) : String(id))
const colPrefix = (col) => `${PREFIX()}/data/${col}/`
const recPrefix = (col, id) => `${colPrefix(col)}${blobId(col, id)}/`
/** unique, time-sortable version name: never written by two requests */
const vname = () => `${String(Date.now()).padStart(14, '0')}-${crypto.randomBytes(4).toString('hex')}`

let queue = Promise.resolve()
const serial = (fn) => (queue = queue.then(fn, fn))

async function fsAll(col) {
  const f = path.join(DATA_DIR, `${col}.json`)
  return existsSync(f) ? JSON.parse(await fs.readFile(f, 'utf8')) : []
}
async function fsWrite(col, list) {
  await fs.mkdir(DATA_DIR, { recursive: true })
  const f = path.join(DATA_DIR, `${col}.json`)
  const tmp = `${f}.${process.pid}.tmp`
  await fs.writeFile(tmp, json(list))
  await fs.rename(tmp, f)
}

const versionsOf = async (col, id) => (await listAll(recPrefix(col, id), priv().token)).sort((a, b) => a.pathname.localeCompare(b.pathname))
const readVersion = async (b) => {
  const p = priv()
  return JSON.parse(p.unwrap(await fetchBlob(b, p.access, p.token)).toString('utf8'))
}
async function writeVersion(col, id, record) {
  const { put } = await blob()
  const p = priv()
  const r = await put(`${recPrefix(col, id)}${vname()}${p.ext}`, p.wrap(json(record)), { access: p.access, token: p.token, contentType: p.type, addRandomSuffix: false, allowOverwrite: false })
  return r
}
/** keeps the newest `keep` versions of a record */
async function prune(vs, keep) {
  if (vs.length <= keep) return
  const { del } = await blob()
  await del(vs.slice(0, vs.length - keep).map((b) => b.url), { token: priv().token }).catch(() => undefined)
}

export async function listRecords(col) {
  if (storageMode() === 'fs') return fsAll(col)
  const map = group(await listAll(colPrefix(col), priv().token), colPrefix(col))
  return pool([...map.values()], 8, (vs) => readVersion(vs.at(-1)))
}

export async function getRecord(col, id) {
  if (storageMode() === 'fs') return (await fsAll(col)).find((r) => r[KEYS[col]] === id) ?? null
  const vs = await versionsOf(col, id)
  return vs.length ? readVersion(vs.at(-1)) : null
}

export async function createRecord(col, id, record) {
  if (storageMode() === 'fs')
    return serial(async () => {
      const list = await fsAll(col)
      if (list.some((r) => r[KEYS[col]] === id)) return null
      list.push(record)
      await fsWrite(col, list)
      return record
    })
  if ((await versionsOf(col, id)).length) return null
  await writeVersion(col, id, record)
  return record
}

export async function updateRecord(col, id, fn) {
  if (storageMode() === 'fs')
    return serial(async () => {
      const list = await fsAll(col)
      const rec = list.find((r) => r[KEYS[col]] === id)
      if (!rec) return null
      if ((await fn(rec)) === false) return rec
      await fsWrite(col, list)
      return rec
    })
  const vs = await versionsOf(col, id)
  if (!vs.length) return null
  const rec = await readVersion(vs.at(-1))
  if ((await fn(rec)) === false) return rec
  await writeVersion(col, id, rec)
  await prune(vs, 4) // + the new one = last 5
  return rec
}

export async function deleteRecord(col, id) {
  if (storageMode() === 'fs')
    return serial(async () => {
      const list = await fsAll(col)
      const rec = list.find((r) => r[KEYS[col]] === id)
      if (!rec) return null
      await fsWrite(
        col,
        list.filter((r) => r !== rec),
      )
      return rec
    })
  const vs = await versionsOf(col, id)
  if (!vs.length) return null
  const rec = await readVersion(vs.at(-1))
  const { del } = await blob()
  await del(
    vs.map((b) => b.url),
    { token: priv().token },
  )
  return rec
}

/** Ids for new records. Disk: running number per year (MK-2026-0007). Blob: date + random (MK-261112-7KQF). */
export async function newQuoteId() {
  const now = new Date()
  if (storageMode() === 'fs') {
    const y = now.getFullYear()
    const n = Math.max(0, ...(await fsAll('quotes')).map((q) => q.id).filter((x) => x.startsWith(`MK-${y}-`)).map((x) => Number(x.slice(8)) || 0)) + 1
    return `MK-${y}-${String(n).padStart(4, '0')}`
  }
  const A = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789' // no 0/O, 1/I
  const rnd = [...crypto.randomBytes(4)].map((b) => A[b % 32]).join('')
  const d = new Intl.DateTimeFormat('sv-SE', { timeZone: 'Europe/Bucharest' }).format(now).slice(2).replace(/-/g, '') // Romanian date
  return `MK-${d}-${rnd}`
}

// ---------- private files (quote attachments) ----------
const fileBlobPath = (stored) => `${PREFIX()}/data/files/${path.basename(stored)}${priv().ext}`

export async function saveDataFile(stored, buf) {
  if (storageMode() === 'fs') {
    await fs.mkdir(FILES_DIR, { recursive: true })
    await fs.writeFile(path.join(FILES_DIR, path.basename(stored)), buf)
    return
  }
  const { put } = await blob()
  const p = priv()
  await put(fileBlobPath(stored), p.wrap(buf), { access: p.access, token: p.token, contentType: p.type, addRandomSuffix: false, allowOverwrite: false })
}

export async function readDataFile(stored) {
  if (storageMode() === 'fs') {
    const f = path.join(FILES_DIR, path.basename(stored))
    return existsSync(f) ? fs.readFile(f) : null
  }
  const p = priv()
  const [b] = await listAll(fileBlobPath(stored), p.token)
  return b ? p.unwrap(await fetchBlob(b, p.access, p.token)) : null
}

export async function deleteDataFile(stored) {
  if (storageMode() === 'fs') {
    await fs.unlink(path.join(FILES_DIR, path.basename(stored))).catch(() => undefined)
    return
  }
  const p = priv()
  const found = await listAll(fileBlobPath(stored), p.token)
  if (found.length) {
    const { del } = await blob()
    await del(
      found.map((b) => b.url),
      { token: p.token },
    ).catch(() => undefined)
  }
}

/** For /api/health: content readable + data writable. */
export async function storageHealth() {
  const checks = { content: false, data: false }
  try {
    JSON.parse((await readContentRaw('company'))?.toString('utf8') || 'x')
    checks.content = true
    if (storageMode() === 'fs') {
      await fs.mkdir(DATA_DIR, { recursive: true })
      await fs.access(DATA_DIR, (await import('node:fs')).constants.W_OK)
    } else {
      if (!publicToken()) throw new Error('no token')
      if (!privateToken()) key() // encryption key available
    }
    checks.data = true
  } catch {
    /* reported */
  }
  return { ...checks, storage: storageMode(), dataProtection: dataProtection() }
}
