/**
 * SecretBackend driver interface.
 *
 * The plaintext backend stores `data` in the DB column directly.
 * Remote backends (openbao, vault, cloud KV) store an opaque `externalRef`
 * and fetch the actual data on demand.
 *
 * Drivers are stateless factories keyed on a `SecretBackend` config row.
 * Secret management (CRUD, naming) stays in the service layer; drivers
 * handle only the storage I/O.
 */

/**
 * Opaque reference written by a driver on `write` and read back on `read`.
 *
 * For the plaintext driver this is unused — the data itself lives in
 * `Secret.data`. For openbao it's a string like `secret/data/mcpctl/mysecret`
 * that tells the driver where to fetch on next `read`.
 */
export type ExternalRef = string;

/** The shape of secret data — a flat map of key → value. */
export type SecretData = Record<string, string>;

export interface SecretBackendDriver {
  /** Human-readable identifier, included in errors. */
  readonly kind: string;

  /**
   * Read the stored secret. For plaintext this is a no-op — the data is
   * already in the Secret row and passed in here for symmetry. For remote
   * backends this makes the network call.
   */
  read(input: { name: string; externalRef: ExternalRef; data: SecretData }): Promise<SecretData>;

  /**
   * Store a new secret (or a new version of an existing one). Returns the
   * reference (or an empty string for plaintext) + the `data` object that
   * should be persisted on the Secret row (empty for remote backends).
   */
  write(input: { name: string; data: SecretData }): Promise<{ externalRef: ExternalRef; storedData: SecretData }>;

  /** Remove the secret from the backend. Idempotent — missing is OK. */
  delete(input: { name: string; externalRef: ExternalRef }): Promise<void>;

  /** List everything the backend knows about. Used for migration + drift detection. */
  list(): Promise<Array<{ name: string; externalRef: ExternalRef }>>;

  /** Optional: health probe. Used by `mcpctl describe secretbackend`. */
  healthCheck?(): Promise<{ ok: boolean; detail?: string }>;
}

/** Stored config for a SecretBackend row; dispatched on `type`. */
export interface BackendRow {
  id: string;
  name: string;
  type: string;
  config: Record<string, unknown>;
}

/**
 * Dependency passed to the openbao driver so it can resolve its own auth
 * token (stored in the plaintext backend — chicken-and-egg bootstrap).
 * Implemented by the SecretService so we don't have a circular import.
 */
export interface SecretRefResolver {
  resolve(secretName: string, key: string): Promise<string>;
}
