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

// src/db/credentials.ts
init_client();
init_ids();
init_clock();
function hydrate(row) {
  const archivedAt = row.archived_at ? toIso(row.archived_at) : null;
  if (row.auth_type === "mcp_oauth") {
    return {
      type: "vault_credential",
      id: row.id,
      vault_id: row.vault_id,
      display_name: row.display_name,
      auth: {
        type: "mcp_oauth",
        mcp_server_url: row.mcp_server_url,
        expires_at: row.expires_at
      },
      created_at: toIso(row.created_at),
      updated_at: toIso(row.updated_at),
      archived_at: archivedAt
    };
  }
  return {
    type: "vault_credential",
    id: row.id,
    vault_id: row.vault_id,
    display_name: row.display_name,
    auth: {
      type: "static_bearer",
      mcp_server_url: row.mcp_server_url
    },
    created_at: toIso(row.created_at),
    updated_at: toIso(row.updated_at),
    archived_at: archivedAt
  };
}
function createCredential(input) {
  const db = getDb();
  const id = newId("cred");
  const now = nowMs();
  const encrypted = encryptValue(input.token);
  const refreshEncrypted = input.refresh_config ? encryptValue(JSON.stringify(input.refresh_config)) : null;
  db.prepare(
    `INSERT INTO vault_credentials (id, vault_id, display_name, auth_type, auth_token_encrypted, mcp_server_url, expires_at, refresh_config_encrypted, created_at, updated_at)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
  ).run(id, input.vault_id, input.display_name, input.auth_type, encrypted, input.mcp_server_url ?? null, input.expires_at ?? null, refreshEncrypted, now, now);
  return getCredential(id);
}
function getCredential(id) {
  const db = getDb();
  const row = db.prepare(`SELECT * FROM vault_credentials WHERE id = ?`).get(id);
  return row ? hydrate(row) : null;
}
function listCredentials(vaultId) {
  const db = getDb();
  const rows = db.prepare(`SELECT * FROM vault_credentials WHERE vault_id = ? ORDER BY created_at DESC`).all(vaultId);
  return rows.map(hydrate);
}
function getCredentialToken(id) {
  const db = getDb();
  const row = db.prepare(`SELECT auth_token_encrypted FROM vault_credentials WHERE id = ?`).get(id);
  if (!row) return null;
  return decryptValue(row.auth_token_encrypted);
}
function listCredentialsWithTokens(vaultId) {
  const db = getDb();
  const rows = db.prepare(`SELECT * FROM vault_credentials WHERE vault_id = ? ORDER BY created_at DESC`).all(vaultId);
  return rows.map((row) => ({
    ...hydrate(row),
    token: decryptValue(row.auth_token_encrypted)
  }));
}
function updateCredential(id, input) {
  const db = getDb();
  const existing = db.prepare(`SELECT * FROM vault_credentials WHERE id = ?`).get(id);
  if (!existing) return null;
  const now = nowMs();
  const parts = ["updated_at = ?"];
  const args = [now];
  if (input.display_name !== void 0) {
    parts.push("display_name = ?");
    args.push(input.display_name);
  }
  if (input.auth_type !== void 0) {
    parts.push("auth_type = ?");
    args.push(input.auth_type);
  }
  if (input.token !== void 0) {
    parts.push("auth_token_encrypted = ?");
    args.push(encryptValue(input.token));
  }
  if (input.mcp_server_url !== void 0) {
    parts.push("mcp_server_url = ?");
    args.push(input.mcp_server_url);
  }
  if (input.expires_at !== void 0) {
    parts.push("expires_at = ?");
    args.push(input.expires_at);
  }
  if (input.refresh_config !== void 0) {
    parts.push("refresh_config_encrypted = ?");
    args.push(input.refresh_config ? encryptValue(JSON.stringify(input.refresh_config)) : null);
  }
  db.prepare(`UPDATE vault_credentials SET ${parts.join(", ")} WHERE id = ?`).run(...args, id);
  return getCredential(id);
}
function archiveCredential(vaultId, credentialId) {
  const db = getDb();
  const existing = db.prepare(`SELECT * FROM vault_credentials WHERE id = ? AND vault_id = ?`).get(credentialId, vaultId);
  if (!existing) return null;
  const now = nowMs();
  db.prepare(`UPDATE vault_credentials SET archived_at = ?, updated_at = ? WHERE id = ?`).run(now, now, credentialId);
  return getCredential(credentialId);
}
function getRefreshConfig(id) {
  const db = getDb();
  const row = db.prepare(
    `SELECT refresh_config_encrypted, auth_type FROM vault_credentials WHERE id = ?`
  ).get(id);
  if (!row || row.auth_type !== "mcp_oauth" || !row.refresh_config_encrypted) return null;
  return JSON.parse(decryptValue(row.refresh_config_encrypted));
}
function deleteCredential(id) {
  const db = getDb();
  const res = db.prepare(`DELETE FROM vault_credentials WHERE id = ?`).run(id);
  return res.changes > 0;
}

export {
  createCredential,
  getCredential,
  listCredentials,
  getCredentialToken,
  listCredentialsWithTokens,
  updateCredential,
  archiveCredential,
  getRefreshConfig,
  deleteCredential
};
