import {
  decryptValue,
  encryptValue
} from "./chunk-AIBH32FN.js";
import {
  init_ids,
  newId
} from "./chunk-F4WUVOLE.js";
import {
  init_clock,
  nowMs
} from "./chunk-HFDLUBWN.js";
import {
  getDb,
  init_client
} from "./chunk-TLEKKGH7.js";

// src/db/upstream_keys.ts
init_client();
init_ids();
init_clock();
import crypto from "crypto";
function hashValue(raw) {
  return crypto.createHash("sha256").update(raw).digest("hex");
}
function toView(r) {
  return {
    id: r.id,
    provider: r.provider,
    prefix: r.prefix,
    weight: r.weight,
    disabled_at: r.disabled_at,
    last_used_at: r.last_used_at,
    created_at: r.created_at
  };
}
function addUpstreamKey(input) {
  const db = getDb();
  const id = newId("ukey");
  const hash = hashValue(input.value);
  const prefix = input.value.slice(0, 10);
  const encrypted = encryptValue(input.value);
  const now = nowMs();
  db.prepare(
    `INSERT INTO upstream_keys (id, provider, hash, prefix, value_encrypted, weight, created_at)
     VALUES (?, ?, ?, ?, ?, ?, ?)`
  ).run(id, input.provider, hash, prefix, encrypted, input.weight ?? 1, now);
  return toView({
    id,
    provider: input.provider,
    hash,
    prefix,
    value_encrypted: encrypted,
    weight: input.weight ?? 1,
    disabled_at: null,
    last_used_at: null,
    created_at: now
  });
}
function listUpstreamKeys(provider) {
  const db = getDb();
  const rows = provider ? db.prepare(`SELECT * FROM upstream_keys WHERE provider = ? ORDER BY created_at DESC`).all(provider) : db.prepare(`SELECT * FROM upstream_keys ORDER BY created_at DESC`).all();
  return rows.map(toView);
}
function selectNextUpstreamKey(provider) {
  const db = getDb();
  const row = db.prepare(
    `SELECT * FROM upstream_keys
         WHERE provider = ? AND disabled_at IS NULL
         ORDER BY last_used_at ASC NULLS FIRST, created_at ASC
         LIMIT 1`
  ).get(provider);
  if (!row) return null;
  db.prepare(`UPDATE upstream_keys SET last_used_at = ? WHERE id = ?`).run(nowMs(), row.id);
  try {
    return { id: row.id, value: decryptValue(row.value_encrypted) };
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    console.warn(
      `[upstream-keys] DISABLING ${row.id} (provider=${row.provider}, prefix=${row.prefix}) \u2014 decryption failed (${msg}). Most likely VAULT_ENCRYPTION_KEY changed since this row was written. Check your .env / secrets, restore the prior VAULT_ENCRYPTION_KEY, or re-add pool keys with the new key.`
    );
    disableUpstreamKey(row.id);
    return null;
  }
}
function disableUpstreamKey(id) {
  const db = getDb();
  const res = db.prepare(`UPDATE upstream_keys SET disabled_at = ? WHERE id = ? AND disabled_at IS NULL`).run(nowMs(), id);
  return res.changes > 0;
}
function enableUpstreamKey(id) {
  const db = getDb();
  const res = db.prepare(`UPDATE upstream_keys SET disabled_at = NULL WHERE id = ?`).run(id);
  return res.changes > 0;
}
function deleteUpstreamKey(id) {
  const db = getDb();
  const res = db.prepare(`DELETE FROM upstream_keys WHERE id = ?`).run(id);
  return res.changes > 0;
}
function getUpstreamKey(id) {
  const db = getDb();
  const row = db.prepare(`SELECT * FROM upstream_keys WHERE id = ?`).get(id);
  return row ? toView(row) : null;
}

export {
  addUpstreamKey,
  listUpstreamKeys,
  selectNextUpstreamKey,
  disableUpstreamKey,
  enableUpstreamKey,
  deleteUpstreamKey,
  getUpstreamKey
};
